简体   繁体   English

创建图形对象

[英]Create Graphics Object

Im trying to create a billiard table with the ball made of colored pixels.我试图用彩色像素制成的球创建一个台球桌。 My problem is I'm trying to make a Graphics Object for the pool table but I don't know how to initialize it I know supposed to use我的问题是我正在尝试为台球桌创建一个图形对象,但我不知道如何初始化它我知道应该使用

PaintEventArgs pe

I have tried我试过了

        base.OnPaint(pe);
        // Declare and instantiate a new pen.
        System.Drawing.Pen myPen = new System.Drawing.Pen(Color.Aqua);

        // Draw an aqua rectangle in the rectangle represented by the control.
        pe.Graphics.DrawRectangle(myPen, new Rectangle(this.Location,
           this.Size));`

but it only creates half a rectangle and it requires a panel.但它只创建了半个矩形并且需要一个面板。 Is this the correct way of doing this, since I am supposed to create a colored ball of pixels?这是这样做的正确方法吗,因为我应该创建一个彩色像素球?

I would recommend creating a control for the billiard table something like this我建议为台球桌创建一个像这样的控件

public class Billiard:Control
{
    public List<Point> Balls { get; private set; } 

    public Billiard()
    {
        Balls=new List<Point>();
    }

    protected override void OnBackColorChanged(EventArgs e)
    {

    }

    protected override void OnPaint(PaintEventArgs e)
    {
        base.OnPaint(e);
        using (var imageBuffer = new Bitmap(Width, Height))
        {
            using (var graphicsObject=Graphics.FromImage(imageBuffer))
            {
                graphicsObject.Clear(Color.Green);

                using (var boundryPen=new Pen(Brushes.SaddleBrown,10))
                {
                    graphicsObject.DrawRectangle(boundryPen,0,0,Width,Height);
                }

                using (var ballPen = new Pen(Brushes.Red, 5))
                {
                    foreach (var ball in Balls)
                    {
                        graphicsObject.DrawEllipse(ballPen,new Rectangle(ball,new Size(5,5)));
                    }
                }

                e.Graphics.DrawImage((Image)imageBuffer.Clone(),0,0);
            }
        }
    }
}

看起来像这样

Obviously you have to validate the location of the balls and other stuff.显然,您必须验证球和其他东西的位置。 Create methods for doing stuff.创建做事的方法。

Have you tried obj.CreateGraphics() method.您是否尝试过obj.CreateGraphics()方法。 for example if you are drawing on the windows form then graphics object will be created like this.例如,如果您在 windows 窗体上绘图,那么图形对象将像这样创建。

Graphics g = this.CreateGraphics();

but if you are drawing on any panel or any control then you can use like this.但是如果你在任何面板或任何控件上绘图,那么你可以像这样使用。

Graphics g = pnlYourPanel.CreateGraphics();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM