[英]How to draw a circle or a line that will always start from the center of the pictureBox?
[英]How do I draw a circle and line in the picturebox?
如何在图片框中绘制圆和线?
或者:
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
e.Graphics.DrawLine(
new Pen(Color.Red,2f),
new Point(0,0),
new Point(pictureBox1.Size.Width, pictureBox1.Size.Height ));
e.Graphics.DrawEllipse(
new Pen(Color.Red, 2f),
0,0, pictureBox1.Size.Width, pictureBox1.Size.Height );
}
处理图片框的绘制事件并在那里进行自定义绘图。
最好的方法是不要在图片框中画圆和线! 它不是为此目的而设计的。
来自 Bob Powell 的 GDI+ 博客:
这个问题的根源在于windows编程的基本规则被打破了。 由于图片框被归咎于真正不是它的错的东西。 为了帮助解释原因,以下四点概述了在这种情况下出了什么问题。
PictureBox 控件用于显示图像。 它不是图形表面的方便占位符。
Windows 是一个事件驱动系统,其中每个事件都必须在正确的上下文中提供服务,并且注定要处理按钮单击或鼠标移动事件的事件不得用于在屏幕上绘制或其他奇怪的东西。
PictureBox 通过绘制存储在它的 Image 属性中的基于 System.Drawing.Image 的对象来刷新自身。 如果没有图像,它将显示背景颜色。
窃取和绘制任何控件的 Graphics 对象都不是好的做法,应该强烈劝阻并违反在正确的时间在正确的位置处理事件的规则。 基本上,如果你这样做,它会给你带来痛苦。 当你用头撞墙时,它会让你感到疼痛。 这是你应该停止这样做的标志。 PictureBox.CreateGraphics 调用也是如此。
正确的做法。
遵循事件驱动系统的规则很容易,但需要一些深谋远虑。 因此,如果您想绘制一些图形,并在窗口在它前面移动并再次移开或最小化和恢复时将其保留在那里,则必须为您希望的任何对象的 Paint 事件提供服务涂上。 PictureBox 随身携带着这种应用程序不需要的包袱。 如果您只想在一个地方绘制某些东西,请通过响应 Form.Paint 事件在表单上绘制它。 如果您想要一个方便的占位符用于在设置范围内工作的图形,请使用 Panel 控件并为其提供 Paint 事件。 如果您想为您的企业形象一遍又一遍地复制图形,请创建一个控件并在 OnPaint 覆盖中进行绘图。
来源: https : //web.archive.org/web/20120330003635/http : //bobpowell.net/picturebox.htm (原站点已不存在)。
图片框是一个控件,并有一个图像作为源 - 所以你必须在图像上绘制并将图像交给控件以显示它
MyImage = new Bitmap(fileToDisplay);
pictureBox1.ClientSize = new Size(xSize, ySize);
pictureBox1.Image = MyImage;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Asssignment
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Graphics g = this.CreateGraphics();
Pen p = new Pen(Color.Blue);
int radius = 200;
int x =Width/2;
int y =Height/2;
int first_point1 = (int)(Math.Cos(0) * radius + x);
int first_point2 = (int)(Math.Sin(0) * radius + y);
Point p1= new Point(first_point1,first_point2);
for(int i=1;i<500; i++)
{
int dx = (int)(Math.Cos(i)*radius+x );
int dy = (int)(Math.Sin(i)*radius+y );
Point p2 = new Point(dx, dy);
g.DrawLine(p, p1, p2);
p1 = p2;
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.