我们有一种将图标转换为给定尺寸的方法,如下所示:
private BitmapFrame GetSizedSource(Icon icon, int size)
{
var stream = IconToStream(icon);
var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand);
var frame = decoder.Frames.SingleOrDefault(_ => Math.Abs(_.Width - size) < double.Epsilon);
return frame;
}
private Stream IconToStream(Icon icon)
{
using (var stream = new MemoryStream())
{
icon.Save(stream);
stream.Position = 0;
return stream;
}
}
当我们传递图标时,height/width
为32,参数size
为32。
实际上,decoder.Frame[0]
宽度/高度 1.0 ,我不知道为什么?
我错过了什么吗?
答案 0 :(得分:0)
问题在于IconToStream
,它会创建MemoryStream
,将图标复制到其中,返回引用,然后处理由MemoryStream
分配的所有资源,从而有效地生成您的流,因此Frame
空。如果您要将“GetSizedSource
更改为下面的内容,则会在发布BitmapFrame
之前返回MemoryStream
:
private BitmapFrame GetSizedSource(Icon icon, int size)
{
using (var stream = new MemoryStream())
{
icon.Save(stream);
stream.Position = 0;
return BitmapDecoder.Create(stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand)
.Frames
.SingleOrDefault(_ => Math.Abs(_.Width - size) < double.Epsilon);
}
}