如何在Image上绘制一个矩形 [英] How to draw a rectangle on Image

查看:79
本文介绍了如何在Image上绘制一个矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想在我的 pictureBox 上画一个矩形9x9,然后保存。我该怎么办?

Hi,
I want to draw a rectangle 9x9 on my pictureBox and then save it. How can I do it?

推荐答案

第一步是创建Graphics对象以用于绘图。您无法直接绘制,您需要创建一个Bitmap,并使用Graphics对象在其上创建不同的东西。



您可以通过将pictureBox(图像)传递给它来创建自己的Bitmap,并通过它创建图形。像这样,



The first step would be to create the Graphics object to work for the drawing. You cannot draw directly, you are required to create a Bitmap, and use the Graphics object to create different things on it.

You can create your own Bitmap, by passing your pictureBox (Image) to it, and make the Graphics by it. Like this,

// suppose bitmap is the object
Graphics gr = Graphics.FromImage(bitmap);





。现在gr将是实际的图形,它代表图像的位图,你现在可以使用它了。你可以在上面画出不同的形状。



要绘制一个简单的矩形,你需要调用 DrawRectangle()函数。





.. now gr would be the actual graphics, that would represent the bitmap of your image and you can now work on it. You can draw different shapes on it.

To draw a simple Rectangle you are required to call DrawRectangle() function.

// pen is used as the color for the borders
// rect is the bounds for the rectangle, pass the 9x9 area to it
gr.DrawRectangle(pen, rect);





..现在它将有矩形它,将这个(更新的)位图实例添加到PictureBox中以在屏幕上显示它或者只保存它。



作为Bill在评论中已经提到过,我想将这条信息添加到我的答案中。在绘制事件 [ ^ ]。当您要向控件添加形状以进行渲染时,会引发Paint事件;相信我没有画家参与。您只需将事件处理程序附加到控件,就像对Click事件一样。



Paint事件处理程序的示例代码在我附加的链接中。



可以找到Graphics对象所有方法的整个目录这里 [ ^ ]。



.. now it will have the rectangle on it, add this (updated) instance of the Bitmap to the PictureBox to show it on the screen or just save it.

As Bill has mentioned in the comments, I would like to add that piece of information to my answer. It is a good approach to add shapes to the graphics object for the image in the Paint Event[^]. Paint event is raised when you're going to add shapes to the control for rendering; trust me there is no painter involved. You can simply just attach an event handler to the control like you do for the Click event.

Example code for the Paint Event handler is in the link I attached.

Entire directory for all of the methods of the Graphics object can be found here[^].


这篇关于如何在Image上绘制一个矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆