我需要生成一个新方法来填充下面的代码中的三角形并分别调用 有什么建议吗?
public void draw(Graphics g, Pen blackPen)
{
double xDiff, yDiff, xMid, yMid;
xDiff = oppPt.X - keyPt.X;
yDiff = oppPt.Y - keyPt.Y;
xMid = (oppPt.X + keyPt.X) / 2;
yMid = (oppPt.Y + keyPt.Y) / 2;
// draw triangle
g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2));
g.DrawLine(blackPen, (int)(xMid + yDiff / 2), (int)(yMid - xDiff / 2), (int)oppPt.X, (int)oppPt.Y);
g.DrawLine(blackPen, (int)keyPt.X, (int)keyPt.Y, oppPt.X, oppPt.Y);
}
该方法应同时使用这两个参数
public void fillTriangle(Graphics g, Brush redBrush)
{
}
答案 0 :(得分:1)
对图形使用单个函数,为降低复杂性和一致性,请使用GraphicsPath
对象。
void DrawGraphics(Graphics g, Pen pen, Brush brush)
{
float xDiff=oppPt.X-keyPt.X;
float yDiff=oppPt.Y-keyPt.Y;
float xMid=(oppPt.X+keyPt.X)/2;
float yMid=(oppPt.Y+keyPt.Y)/2;
// Define path with the geometry information only
var path = new GraphicsPath();
path.AddLines(new PointF[] {
keyPt,
new PointF(xMid + yDiff/2, yMid-xDiff/2),
oppPt,
});
path.CloseFigure();
// Fill Triangle
g.FillPath(brush, path);
// Draw Triangle
g.DrawPath(pen, path);
}
结果如下所示:
答案 1 :(得分:-1)
您只需要创建一个带有点的数组,然后配置填充方式,然后是绘制FillPolygon
,它是实体DrawPolygon
的轮廓。
public void draw(Pen blackPen)
{
Graphics draw = CreateGraphics();
Point[] points = new Point[6];
points[0].X = 0;
points[0].Y = 0;
points[1].X = 150;
points[1].Y = 150;
points[2].X = 0;
points[2].Y = 150;
using (SolidBrush fillvar = new SolidBrush(Color.FromArgb(100, Color.Yellow)))
{
draw.FillPolygon(fillvar, points.ToArray());
draw.DrawPolygon(Pens.DarkBlue, points);
}
}
如果要将FillPolygon
绘制在某物内部,例如PictureBox
,则只需将其分配给Graphics draw
。
Graphics draw = picturebox.CreateGraphics();
以上只是有关其工作原理的实际说明,请看一下您的代码。缺少只是实现其xDiff,yiff,xMid,yMid坐标。
public void draw(Graphics g, Pen blackPen)
{
double xDiff, yDiff, xMid, yMid;
Point[] points = new Point[6];
points[0].X = 50;
points[0].Y = 50;
points[1].X = 150;
points[1].Y = 150;
points[2].X = 0;
points[2].Y = 150;
SolidBrush varbrush = new SolidBrush(Color.FromArgb(100, Color.Yellow));
fillTriangle(g, varbrush, points);
}
您必须将点传递到fillTriangle并以这种方法绘制它们。
public void fillTriangle(Graphics g, Brush varbrush, Point[] points)
{
g.FillPolygon(varbrush, points.ToArray());
g.DrawPolygon(Pens.Red, points);
}