一、创建画布
方法1:
Graphics g = this.CreateGraphics();
方法2:
Bitmap bitmap = new Bitmap(picBTrackReplay.Width, picBTrackReplay.Height); Graphics g = Graphics.FromImage(bitmap);
picBTrackReplay.Image = bitmap;//指定控件图片
另外使用using,可自动对画布进行资源回收。
二、创建画笔
1、创建画笔
using (Pen blackPen = new Pen(Color.Black, 2)) { // 绘制语句 }
2、自定义虚线的间隔
Pen gridPen = new Pen(color, 1); float[] d = new float[2]; d[0] = 3; d[1] = 3; gridPen .DashPattern = d; gridPen .DashStyle = DashStyle.Custom;
3、自定义箭头格式
AdjustableArrowCap lineCap = new AdjustableArrowCap(4, 4, true); Pen yellowPen = new Pen(Color.Yellow, 2); yellowPen.CustomEndCap = lineCap;
三、绘图
List<PointF> changedPointsList=new List<PointF>();
// 画线 g.DrawLines(redPen, changedPointsList.ToArray());
//g.DrawLine(redPen, new PointF(1,2),new PointF(3,4));
// 画矩形
g.DrawRectangle(redPen,new PointF(1,2),1,1);
// 绘制多边形
g.DrawPolygon(redPen,changedPointsList.ToArry());
// 绘制文字
g.DrawString("string", new Font("宋体", 9), Brushes.Black, new PointF(1,2));
// 填充颜色
g.FillPolygon(Brushes.Black,changedPointsList.ToArry());
四、画布坐标平移
屏幕坐标:
以屏幕左上角为原点,横向为X轴,竖向为Y轴。
// 改变原点位置
g.TranslateTransform(dx,dy); // 翻转Y轴 g.ScaleTransform(1, -1);