如何从WPF中的多分辨率.ico文件中选择正确的大小图标? [英] How do you select the right size icon from a multi-resolution .ico file in WPF?

查看:1868
本文介绍了如何从WPF中的多分辨率.ico文件中选择正确的大小图标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个多分辨率图标文件(.ico),我怎样才能确保WPF选择合适尺寸的文件?设置Image的宽度和高度是否会强制它,或者WPF是否只调整ico文件中的第一个图标?

If I have a multi-resolution icon file (.ico), how can I insure that WPF picks the right sized one? Does setting the width and height of the Image force it, or does WPF simply resize the first icon in the ico file?

这是我目前正在使用的(它有效,但我想避免调整大小,如果这是正在发生的事情。)

This is what I'm using currently (it works, but I'd like to avoid the resizing if that's what's happening).

<MenuItem.Icon>
    <Image Source="MyIcons.ico" Width="16" Height="16"  />
</MenuItem.Icon>

如果可能,我想在Xaml中声明这一点,而无需为其编码。

I'd like to declare this in Xaml if possible without having to code for it.

推荐答案

我使用简单的标记扩展:

I use simple Markup Extension for that:

/// <summary>
/// Simple extension for icon, to let you choose icon with specific size.
/// Usage sample:
/// Image Stretch="None" Source="{common:Icon /Controls;component/icons/custom.ico, 16}"
/// Or:
/// Image Source="{common:Icon Source={Binding IconResource}, Size=16}"
/// </summary> 
public class IconExtension : MarkupExtension
{
    private string _source;

    public string Source
    {
        get
        {
            return _source;
        }
        set
        {
            // Have to make full pack URI from short form, so System.Uri recognizes it.
           _source = "pack://application:,,," + value;
        }
    }

    public int Size { get; set; }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        var decoder = BitmapDecoder.Create(new Uri(Source), 
                                           BitmapCreateOptions.DelayCreation,
                                           BitmapCacheOption.OnDemand);

        var result = decoder.Frames.SingleOrDefault(f => f.Width == Size);
        if (result == default(BitmapFrame))
        {
            result = decoder.Frames.OrderBy(f => f.Width).First();
        }

        return result;
    }

    public IconExtension(string source, int size)
    {
        Source = source;
        Size = size;
    }

    public IconExtension() { }
}

Xaml用法:

<Image Stretch="None"
       Source="{common:Icon Source={Binding IconResource},Size=16}"/>

<Image Stretch="None"
       Source="{common:Icon /ControlsTester;component/icons/custom-reports.ico, 16}" />

这篇关于如何从WPF中的多分辨率.ico文件中选择正确的大小图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆