如何在图像中绘制线条?

时间:2018-05-19 20:23:12

标签: c# wpf

有这样一个脚本(它在给定坐标处绘制一个三角形并将其插入图像中) -

int[] xPoints = new int[] { Convert.ToInt32(AX), Convert.ToInt32(BX), Convert.ToInt32(CX) };      
int[] yPoints = new int[] { Convert.ToInt32(AY), Convert.ToInt32(BY), Convert.ToInt32(CY) };

int xMin = 0;
int yMin = 0;
if(xPoints.Min() < 0)
{
    xMin = xPoints.Min();
}
if(yPoints.Min() < 0)
{
    yMin = yPoints.Min();
}

int height = (yPoints.Max() + (-yMin)) * 100;
int width = (xPoints.Max() + (-xMin)) * 100;//I set the boundaries and increase the size of the image (that would not be 6x3 pixels)

Image myImage = new Image();

DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawLine(new Pen(Brushes.Green, 1), new Point(CX, CY  ), new Point(BX  , BY  ));
drawingContext.DrawLine(new Pen(Brushes.Black, 1), new Point(CX, CY  ), new Point(AX  , AY  ));
drawingContext.DrawLine(new Pen(Brushes.Red, 1), new Point(AX * 300, AY * 300), new Point(BX * 300, BY * 300));


drawingContext.Close();

RenderTargetBitmap bmp = new RenderTargetBitmap(width, height, 100, 100, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
myImage.Source = bmp;

MainCanvas.Children.Add(myImage);

using (FileStream stream = new FileStream("Sample.png", FileMode.Create))
{
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bmp));
    encoder.Save(stream);
}

我画线条,结果就是这样 -

problem triangle

为什么会这样?有什么必要乘以x,y(创建一个Point时)以使三角形完全适合其边界?它将是通用的,也就是说,如果我改变坐标,一切都会正常工作。此外,未绘制CB线。我怀疑它是由于它是在图像的边界。如果我制作无限大小的画笔(2000),那么这条线将占据整个图像,如果更少,则根本不绘制。

0 个答案:

没有答案