更新时间:2022-10-29 14:06:39
DrawingContext完成的绘图大小(Rectangle)与UIElement的大小不同。 Image类和UIElement类都没有属性可以获得绘图的大小。您可以定义自己的自定义属性,以便能够获得绘制的矩形的高度和宽度:public class MyImage:Image
{
protected 覆盖 void OnRender(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Red, null , new Rect( 0 , 0 , 100 , 100 ));
此 .RectHeight = 100 ;
此 .RectWidth = 100 ;
}
public double RectHeight {获得跨度>; private set ; }
public double RectWidth { get 跨度>; private set ; }
}
资料来源:
https://social.msdn.microsoft.com/Forums/en-US / 2f512dd6-cf81-46a6-ab38-e9f7cc483030 / wpf-how-to-get-a-custom-image-actualwidth-value [ ^
Goal: To get an ActualWidth value of a custom image.
Problem: The ActualWidth value is always 0.
Question: How to get a right custom image ActualWidth value?
Code:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
MyImage myimage = new MyImage();
MessageBox.Show(myimage.ActualWidth.ToString()); // 0
}
}
class MyImage : Image
{
protected override void OnRender(DrawingContext dc)
{
dc.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100));
}
}
The size of the drawing (Rectangle) done by the DrawingContext is not the same thing as the size of the UIElement. There are no properties of the Image class nor the UIElement class that gets you the size of the drawing. You could define your own custom properties to be able to get the Height and Width of the drawn Rectangle:public class MyImage : Image { protected override void OnRender(DrawingContext dc) { dc.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100)); this.RectHeight = 100; this.RectWidth = 100; } public double RectHeight { get; private set; } public double RectWidth { get; private set; } }
Source:
https://social.msdn.microsoft.com/Forums/en-US/2f512dd6-cf81-46a6-ab38-e9f7cc483030/wpf-how-to-get-a-custom-image-actualwidth-value[^]