Reputation: 377
I'm currently facing a problem showing a transparent image in a Xamarin.Forms Image view.
Result (top), and original (bottom), taken on Android: Screenshot
The goal is to show the Image with a transparent background, but I can't get it to work. It keeps showing with a black background. Loading a transparent PNG file from internet works, so something in the process of conversion or image processing must go wrong.
Image retrieval and conversion:
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);
Transparency added:
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;
}
Conversion to imagesource:
return SKBitmapImageSource.FromStream(SKImage.FromBitmap((SKBitmap)value).Encode().AsStream);
Upvotes: 2
Views: 2440
Reputation: 56
The problem is the AlphaType being set incorrectly. For the way you're doing the alpha conversion, the AlphaType should be set to AlphaType.Premul
Since it's a readonly property, copy the bitmap to a new one and set the correct alpha type
Upvotes: 3