我有一些问题。
我正在尝试将 png-image 从资源加载到 viewModel 中的 BitmapImage 属性,如下所示:
Bitmap bmp = Resource1.ResourceManager.GetObject(String.Format("_{0}",i)) as Bitmap;
MemoryStream ms = new MemoryStream();
bmp.Save(ms, ImageFormat.Bmp);
BitmapImage bImg = new BitmapImage();
bImg.BeginInit();
bImg.StreamSource = new MemoryStream(ms.ToArray());
bImg.EndInit();
this.Image = bImg;
但当我这样做时,我失去了图像的透明度。
所以问题是如何从资源中加载 png 图像而不丢失透明度?
谢谢,
帕维尔.
Ria 的回答帮助我解决了透明度问题。这是适合我的代码:
public BitmapImage ToBitmapImage(Bitmap bitmap)
{
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Png); // Was .Bmp, but this did not show a transparent background.
stream.Position = 0;
BitmapImage result = new BitmapImage();
result.BeginInit();
// According to MSDN, "The default OnDemand cache option retains access to the stream until the image is needed."
// Force the bitmap to load right now so we can dispose the stream.
result.CacheOption = BitmapCacheOption.OnLoad;
result.StreamSource = stream;
result.EndInit();
result.Freeze();
return result;
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)