为SKBitmap图像添加透明度,结果是黑色背景。

问题描述 投票:0回答:1

我目前面临着在Xamarin.Forms图像视图中显示一个透明图像的问题。

  1. 该图片是从图库中获取的,并转换为PNG格式。
  2. 像素被迭代,其中一些像素的alpha值被调整。
  3. 位图被转换为SKBitmapImageSource并显示在图像视图中。

结果(上)和原图(下),在Android上拍摄。截图

我的目标是用透明的背景显示图像,但我不能让它工作。它一直以黑色背景显示。从互联网上加载一个透明的PNG文件可以工作,所以在转换过程中或图像处理过程中一定有问题。

图片检索和转换。

SKBitmap source = SKBitmap.Decode(file.GetStream());
SKData data = SKImage.FromBitmap(source).Encode(SKEncodedImageFormat.Png, 100);
SKBitmap converted = SKBitmap.Decode(data);
SKBitmap result = ImageProcessor.AddTransparency(converted, 0.7f);

增加透明度

    public static SKBitmap AddTransparency(SKBitmap bitmapSource, float treshold)
    {
        if (bitmapSource == null)
        {
            throw new ArgumentNullException(nameof(bitmapSource), $"{nameof(bitmapSource)} is null.");
        }

        var bitmapTarget = bitmapSource.Copy();

        // Calculate the treshold as a number between 0 and 255
        int value = (int)(255 * treshold);

        // loop trough every pixel
        int width = bitmapTarget.Width;
        int height = bitmapTarget.Height;

        for (int row = 0; row < height; row++)
        {
            for (int col = 0; col < width; col++)
            {
                var color = bitmapTarget.GetPixel(col, row);

                if (color.Red > value && color.Green > value && color.Blue > value)
                {
                    bitmapTarget.SetPixel(col, row, color.WithAlpha(0x00));
                }
            }
        }

        return bitmapTarget;
    }

转换为图像源。

return SKBitmapImageSource.FromStream(SKImage.FromBitmap((SKBitmap)value).Encode().AsStream);
c# image-processing xamarin.forms .net-standard skiasharp
1个回答
0
投票

问题是AlphaType设置不正确。对于你进行alpha转换的方式,AlphaType应该设置为AlphaType.Premul。

因为它是一个可读属性,所以将位图复制到一个新的位图,并设置正确的alpha类型。

© www.soinside.com 2019 - 2024. All rights reserved.