在拉伸的图像上绘制符号. [英] Draw symbols on the stretched image.
问题描述
我只需要在拉伸的图像上单击鼠标即可绘制"O"和"X"之类的符号.我正在使用PictureBox和Windows窗体.
我尝试过这样的事情.
Hi,
I need to draw symbols like ''O'' and ''X'' just with a mouse click on the stretched image. Am using PictureBox and windows form.
i tried something like this.
private void pictureBox1_MouseClick(object sender, MouseEventArgs e1)
{
if ((e1.Button & MouseButtons.Left) == MouseButtons.Left)
{
Bitmap b = (Bitmap)pictureBox1.Image;
pictureBox1.Image = b;
Graphics g = Graphics.FromImage(b);
p = new Point(e1.X, e1.Y);
Pen p3 = new Pen(Color.Red, 2);
this.Text = p.ToString();
g.DrawEllipse(p3, p.X, p.Y, 15, 15);
pictureBox1.Invalidate();
}
}
问题是圆是从鼠标单击的点画出的.我认为这是因为图像拉伸.请帮助.
Problem is the circle is drawn away from the mouse clicked point. I think its because of image stretch. Please help.
推荐答案
1)您需要声明"p":
1) You need to declare "p":
Point p = new Point(e1.X, e1.Y);
2)您需要处理所有创建的Graphics和Pen对象-否则将导致以后出现问题.
3)椭圆的起点始终是左上角:尝试补偿它们:
2) You need to dispose of all the Graphics, and Pen objects you create - not doing that will cause problems later.
3) The start point for a Ellipse is always the top left corner: Try offseting them:
g.DrawEllipse(p3, p.X - 7, p.Y - 7, 15, 15);
来自OP:
"pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;"
现在,这是相关信息!
使用PictureBoxSizeMode.StretchImage
时,也会对所有图形操作应用变换,以使其适当缩放为调整大小的图像.你不要那个!
而是使用此:
From OP:
"pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;"
Now, that is relevant information!
When you use PictureBoxSizeMode.StretchImage
you apply a transform too all graphics operations, to make them scale appropriatly into the re-sized image. You don''t want that!
Instead use this:
//pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
using (Image source = Image.FromFile(@"F:\Temp\BTC.jpg"))
{
Image resized = new Bitmap(source, pictureBox1.Size);
pictureBox1.Image = resized;
}
并根据以上建议修改您的Mouse Click事件:
And modify your Mouse Click event as per the suggestions above:
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
{
Bitmap b = (Bitmap) pictureBox1.Image;
pictureBox1.Image = b;
using (Graphics g = Graphics.FromImage(b))
{
Point p = new Point(e.X, e.Y);
using (Pen p3 = new Pen(Color.Red, 2))
{
this.Text = p.ToString();
g.DrawEllipse(p3, p.X - 7, p.Y - 7, 15, 15);
}
}
pictureBox1.Invalidate();
}
}
严重的是,以后不处理对象(尤其是与图形相关的对象)会导致无法预料的问题-如果直到编写和测试此代码后两周才出现问题,很难弄清问题是什么!
Seriously, not disposing of objects (particularly graphics related objects) causes unpredictable problems later on - it can be very hard to work out what the problem is if it doesn''t occur until two weeks after you wrote and tested this code!
这篇关于在拉伸的图像上绘制符号.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!