Drawing上的DrawingContext DrawGeometry(wpf)

时间:2016-10-03 17:52:27

标签: c# wpf canvas

我尝试以编程方式在我的WPF项目中绘制一个带圆角的矩形。我对WPF很新,并试图弄清楚绘图是如何工作的,因为它与WinForms有很大的不同。我正在使用>this<链接作为圆角矩形方法(我的方法与该网站上的方法相同)。这是我的代码:

Rect rect = new Rect();
rect.Width = Width - BorderSize;
rect.Height = Height - BorderSize;

DrawingVisual drawingVisual = new DrawingVisual();
using (var draw = drawingVisual.RenderOpen())
{
    DrawRoundedRectangle(draw, new SolidColorBrush(Color.FromRgb(0, 0, 0)),
    new Pen(new SolidColorBrush(Color.FromRgb(0, 0, 0)), BorderSize), rect, new CornerRadius(5, 5, 5, 5));
}

ContentPresenter content = new ContentPresenter();
content.Content = drawingVisual;
previewcanvas.Children.Add(content);

这是我在画布上的输出:

enter image description here

不是我所期待的;)不应该有任何文字开头。

希望有人可以帮我绘制圆角矩形!

修改

一些额外的信息,我需要能够设置每个角落。

3 个答案:

答案 0 :(得分:1)

        Rect rect = new Rect();
        rect.Width = Width - BorderSize;
        rect.Height = Height - BorderSize;
        DrawingVisual drawingVisual = new DrawingVisual();
        using (var draw = drawingVisual.RenderOpen())
        {
            DrawRoundedRectangle(draw, new SolidColorBrush(Color.FromRgb(0, 0, 0)),
            new Pen(new SolidColorBrush(Color.FromRgb(0, 0, 0)), BorderSize), rect, new CornerRadius(5, 5, 5, 5));
        }
        RenderTargetBitmap rtb = new RenderTargetBitmap(rect.Width, rect.Height, 96, 96, PixelFormats.Default);
        rtb.Render(drawingVisual);
        Image image = new Image();
        image.Source = rtb;
        previewcanvas.Children.Add(image);

答案 1 :(得分:0)

使用RadiusX和RadiusY:

  rect = new Rectangle
        {
            Stroke = Brushes.Red,
            StrokeThickness = 2,
            Width = 100,
            Height = 100,
            RadiusX = 25,
            RadiusY = 25
        };
        Canvas.SetLeft(rect, startPoint.X);
        Canvas.SetTop(rect, startPoint.X);
        canvas.Children.Add(rect);

的Xaml:

  <Canvas x:Name="canvas"/>

答案 2 :(得分:0)

搜索后我找到了一个更简单的解决方案:

Border border = new Border();

border.BorderThickness = new Thickness(2);
border.CornerRadius = new CornerRadius(5,15,25,35);
border.BorderBrush = (SolidColorBrush)(new BrushConverter().ConvertFrom("#000"));
border.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#000"));
border.Width = 100;
border.Height = 100;
border.Margin = new Thickness(10);

previewcanvas.Children.Add(border);

这是一种欺骗(因为它不是一个矩形),但它有效。这是我的结果:

enter image description here