以编程方式设置图标大小

时间:2016-10-13 09:07:18

标签: wpf user-interface

在WPF上我在运行时动态创建一个菜单项。

我从存储在ResourceDictionary上的StreamGeometry设置图标。一切正常,但是:我如何设置图标的大小?

MenuItem menExit = new MenuItem();
menExit.Header = "Exit"; // will be changedlater
menExit.Command = UICommands.CmdExit;
menExit.CommandBindings.Add(new CommandBinding(UICommands.CmdExit, CmdExitExecute, CmdExitCanExecute));
menExit.Icon = (StreamGeometry)FindResource("ImgExit");

//SET THE SIZE HERE????????
// Eventually, how do I set the fill color?

menu.Items.Add(menExit);

注意,我在运行时而不是在xalm

中完成所有这些操作

2 个答案:

答案 0 :(得分:2)

我建议您创建一个路径,您可以在其中指定HeightWidthFill,并将StreamGeometry设置为路径的Data 。然后将此Path作为MenuItem的图标。

var path = new Path
{
    Height = 20,
    Width = 20,
    Fill = new SolidColorBrush(Colors.Blue),
    Data = (StreamGeometry) FindResource("ImgExit")
};
menExit.Icon = path;

答案 1 :(得分:0)

您可以随时尝试:

/// <summary>
/// Convert Geometry to ImageSource, Draws the Geometry on a bitmap surface and centers it.
/// </summary>
/// <param name="geometry"></param>
/// <param name="TargetSize"></param>
/// <returns></returns>
ImageSource Geometry_To_ImageSource(Geometry geometry, int TargetSize)
{
   var rect = geometry.GetRenderBounds(new Pen(Brushes.Black, 0));

   var bigger = rect.Width > rect.Height ? rect.Width : rect.Height;
   var scale = TargetSize / bigger;

   Geometry scaledGeometry = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, new ScaleTransform(scale, scale));
   rect = scaledGeometry.GetRenderBounds(new Pen(Brushes.Black, 0));

   Geometry transformedGeometry = Geometry.Combine(scaledGeometry, scaledGeometry, GeometryCombineMode.Intersect, new TranslateTransform(((TargetSize - rect.Width) / 2) - rect.Left, ((TargetSize - rect.Height) / 2) - rect.Top));

   RenderTargetBitmap bmp = new RenderTargetBitmap(TargetSize, TargetSize, 96, 96, PixelFormats.Pbgra32);

   DrawingVisual viz = new DrawingVisual();
   using (DrawingContext dc = viz.RenderOpen())
   {
      dc.DrawGeometry(Brushes.Black, null, transformedGeometry);
   }

   bmp.Render(viz);

   var mem = new MemoryStream();
   PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
   pngEncoder.Frames.Add(BitmapFrame.Create(bmp));
   pngEncoder.Save(mem);
   var itm = GetImg(mem);
   return itm;
}

BitmapImage GetImg(MemoryStream ms)
{
   var bmp = new BitmapImage();    
   bmp.BeginInit();
   bmp.StreamSource = ms;
   bmp.EndInit();

   return bmp;
}