问题
I have two methods that draw a rotated rectangle on the screen.
RenderMethod1 renders a rectangle rotated by 30 degrees using a DrawingVisual
private static void RenderMethod1(DrawingContext dc) {
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext context = drawingVisual.RenderOpen()) {
Rect rect = new Rect(new System.Windows.Point(100, 100), new System.Windows.Size(320, 80));
context.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);
}
drawingVisual.Transform = new RotateTransform(30, 100, 100);
dc.DrawDrawing(drawingVisual.Drawing);
}
RenderMethod2 renders a rectangle rotated by 30 degrees using a DrawingGroup
private static void RenderMethod2(DrawingContext dc) {
DrawingGroup group = new DrawingGroup();
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext context = drawingVisual.RenderOpen()) {
Rect rect = new Rect(new System.Windows.Point(100, 100), new System.Windows.Size(320, 80));
context.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);
}
group.Children.Add(drawingVisual.Drawing);
group.Transform = new RotateTransform(30, 100, 100);
group.Freeze();
dc.DrawDrawing(group);
}
The output is as follows:
RenderMethod1
RenderMethod2
As you can see RenderMethod1 and RenderMethod2 outputs are supposed to be exactly the same but they are not. Is there anything I am doing wrong in RenderMethod1?
Thanks for help in advance,
回答1:
I finally got around the problem by changing RenderMethod1 as follow and it works as expected.
private static void RenderMethod1(DrawingContext dc) {
DrawingGroup drawingVisual = new DrawingGroup();
using (DrawingContext context = drawingVisual.Open()) {
Rect rect = new Rect(new System.Windows.Point(100, 100), new System.Windows.Size(320, 80));
context.DrawRectangle(System.Windows.Media.Brushes.LightBlue, (System.Windows.Media.Pen)null, rect);
}
drawingVisual.Transform = new RotateTransform(30, 100, 100);
dc.DrawDrawing(drawingVisual);
}
来源:https://stackoverflow.com/questions/8565002/drawinggroup-vs-drawingvisual-transform