各位大小夥伴,六一快樂!
今天又是煩人的雷雨天,想寫點什麼還真不好想,便總結下C#一些成圖的方法:
在C#中,自帶的畫布本身是一個比較簡單的畫圖工具,直接上代碼:
public class DrawUnint
{
Bitmap bitmap;
Graphics g;
double dCenterX;
double dCenterY;
double scale;
public void Save_photo(string path)
{
//System.IO.File.Delete(path);
bitmap.Save(path);
g.Clear(Color.White);
}
public void Ini(point minLimit, point maxLimit)
{
double Xmin = Math.Min(minLimit.x, maxLimit.x);
double Xmax = Math.Max(minLimit.x, maxLimit.x);
double Ymin = Math.Min(minLimit.y, maxLimit.y);
double Ymax = Math.Max(minLimit.y, maxLimit.y);
dCenterX = (Xmax + Xmin) / 2;
dCenterY = (Ymax + Ymin) / 2;
double X_deta = Xmax - Xmin;
double Y_deta = Ymax - Ymin;
if (X_deta == 0) X_deta = 100;//X方向只有一個值
if (Y_deta == 0) Y_deta = 100;//Y方向只有一個值
int bHeight = 2400;
scale = bHeight / Y_deta;
int bWidth = (int)(X_deta * scale);
//scale = bWidth / X_deta * 0.8;
//int bHeight = (int)(Y_deta * scale / 0.8);
bitmap = new Bitmap(bWidth, bHeight);
g = Graphics.FromImage(bitmap);
g.FillRectangle(Brushes.White, new Rectangle(0, 0, bWidth, bHeight));
g.TranslateTransform(bWidth / 2, bHeight / 2);
}
public void DrawPoint(PointDraw p, float width = 5)
{
g.FillEllipse(p.color, (float)((p.x - dCenterX) * scale), (float)((dCenterY - p.y) * scale), width, width);
}
public void DrawPoints(List<point> lp)
{
foreach (var p in lp)
{
g.FillEllipse(p.color, (float)((p.x - dCenterX) * scale), (float)((dCenterY - p.y) * scale), 8, 8);
}
}
public void DrawPath(PointDraw p1, PointDraw p2, Color color, string pentype = "虛線", float width = 6)
{
using (Pen pen = new Pen(color, width))
{
//solid 實線
//Dash 虛線
if (pentype == "虛線") { pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dash; }//虛線
else { pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Solid; }
pen.Color = color;
g.DrawLine(pen, (float)((p1.x - dCenterX) * scale), (float)((dCenterY - p1.y) * scale), (float)((p2.x - dCenterX) * scale), (float)((dCenterY - p2.y) * scale));
}
}
public void DrawCircle(PointDraw circleCenter, double R, double angle_QD, double angle_ZD, Color color, float width = 10)
{
Pen pe = new Pen(color, width);
g.DrawArc(pe, (float)((circleCenter.x - dCenterX) * scale), (float)((dCenterY - circleCenter.y) * scale), 2 * (float)(R * scale), 2 * (float)(R * scale), (float)angle_QD, (float)angle_ZD);
}
public void DrawString(string s, Font font, Brush brush, double x, double y, float angle)
{
//font = new Font("宋體",20);
SizeF sizef = g.MeasureString(s, font);
float dx = (float)((x - dCenterX) * scale);
float dy = (float)((dCenterY - y) * scale);
g.TranslateTransform(dx, dy);
g.RotateTransform(angle);
g.DrawString(s, font, brush, 0, 0);
g.RotateTransform(-angle);
g.TranslateTransform(-dx, -dy);
}
}
這裏便涉及到從圖片創建到初始化,以及畫點、畫線、畫圓、寫字等方法的操作再到另存爲圖片,裏頭的屬性也很容易明白,無非是橢圓的長短半軸、線寬、顏色等屬性。這便是C#利用畫布畫圖的方法。
20200601 星期一21:30