向 SKBitmap 图像添加透明度会导致黑色背景

Adding transparency to a SKBitmap image results in black background

我目前遇到在 Xamarin.Forms 图像视图中显示透明图像的问题。

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

结果(顶部)和原始(底部),拍摄于 Android: Screenshot

目标是显示具有透明背景的图像,但我无法让它工作。它一直以黑色背景显示。从网上加载透明的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);

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

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