【发布时间】:2020-08-13 06:51:40
【问题描述】:
我目前在 Xamarin.Forms 图像视图中显示透明图像时遇到问题。
- 从图库中检索图像,并将其转换为 PNG 格式。
- 像素会被迭代,其中一些像素会调整其 alpha 值。
- 位图转换为 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);
【问题讨论】:
-
确保黑色是真正的黑色。包括 irfanview 在内的许多图像查看器无法显示透明度并将其显示为黑色..
-
尝试将像素点除alpha值为0以外为真黑,但没有成功。
标签: c# image-processing xamarin.forms .net-standard skiasharp