public class CustomGDI
{
/// <summary>
/// 图片宽
/// </summary>
public int Width { get; set; }
/// <summary>
/// 图片高
/// </summary>
public int Height { get; set; }
private IntPtr _pointer { get; set; }
/// <summary>
/// 构造函数
/// </summary>
public CustomGDI()
{
}
/// <summary>
/// 设置图片大小
/// </summary>
/// <param name="width">图片宽</param>
/// <param name="height">图片高</param>
public void SetImagePtr(int width, int height)
{
Width = width;
Height = height;
}
/// <summary>
/// 画图
/// </summary>
/// <param name="graphicContext"></param>
/// <param name="action">委托,添加文本、图像等</param>
/// <param name="zoomX">显示比例</param>
/// <param name="zoomY">显示比例</param>
/// <param name="panX">显示位置</param>
/// <param name="panY">显示位置</param>
public void Draw(Graphics graphicContext, Action<Graphics> action, float zoomX, float zoomY, int panX, int panY)
{
lock(this)
{
int w_x = (int)(this.Width * zoomX);
int h_y = (int)(this.Height * zoomY);
var rect = new Rectangle(panX, panY, w_x, h_y);
using (BufferedGraphicsContext currentContext = BufferedGraphicsManager.Current)
{
using (BufferedGraphics myBuffer = currentContext.Allocate(graphicContext, rect))
{
using (Graphics g = myBuffer.Graphics)
{
if (action != null)
action(g);
// 如果某个缓冲区已被分配但尚未释放,则释放当前的图形缓冲区。
currentContext.Invalidate();
// 呈现图像至关联的Graphics
myBuffer.Render(graphicContext);
}
}
}
}
}
}
使用例子:
Bitmap bm = new Bitmap(customGDI.Width, customGDI.Height);
using (Graphics g = Graphics.FromImage(bm))
{
int x = 0, y = 0, i;
customGDI.Draw(g, (Graphics gg) =>
{
Pen p = new Pen(Color.Red);
Brush b = new SolidBrush(Color.Red);
int t = random.Next(0, 4);
for (i = 0; i < 4; i++)
{
a = a + i * 90 * Math.PI / 180;
x = 320 + (int)(302.5 * Math.Cos(a));
y = 320 + (int)(302.5 * Math.Sin(a));
if (!indexs.Any(t => t == i))
continue;
Rectangle rect = new Rectangle(x, y, 15, 15);
gg.DrawEllipse(p, rect);
gg.FillEllipse(b, rect);
gg.DrawString($"序号{i + 1}", new Font("宋体", 12), Brushes.Green, new PointF(x + 15, y + 10));
gg.DrawEllipse(p, new Rectangle(10, 10, bm.Width - 20, bm.Height - 20));
gg.DrawEllipse(p, new Rectangle(30, 30, bm.Width - 60, bm.Height - 60));
if(i== t)
{
gg.DrawLine(p, new Point((int)(bm.Width / 2), (int)(bm.Height / 2)), new Point(x, y));
}
}
PointF[] pointFs = new PointF[100];
double r = -Math.PI;
bool status = false;
for (i = 0; i < pointFs.Length; i++)
{
x = 330 + (int)(303 * Math.Cos(r));
y = 330 + (int)(290 * Math.Sin(r));
if (status)
y += 3;
else
y -= 3;
status = !status;
pointFs[i] = new PointF(x, y);
r -= 0.01;
}
gg.DrawLines(p, pointFs);
}, 1f, 1f, 0, 0);
//bm.Save(@"C:\\Users\\JS114295\\Desktop\\images\kkk1.jpg", ImageFormat.Jpeg);
this.pictureBox1.Image = bm;