在iPhone中绘制并填充矩形

时间:2011-09-21 09:07:26

标签: iphone core-graphics

我有4分说(x1,y1),(x2,y2),(x2,y3)和(x4,y4)。我需要绘制一个带有这些点的矩形并在该矩形内填充一种颜色。谁能帮我这个?

3 个答案:

答案 0 :(得分:23)

首先,获取当前的图形上下文:

CGContextRef context = UIGraphicsGetCurrentContext();

接下来,定义矩形:

CGRect myRect = {x1, y1, x2 - x1, y2 - y1};

现在,设置填充颜色,例如红色

CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);

设置笔触颜色,例如绿色:

CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0);

最后,填充矩形:

CGContextFillRect(context, myRect);

答案 1 :(得分:2)

创建一个UIBezierPath对象。移至第一个点,然后为随后的三个点调用addLineToPoint:。然后拨打closePath

您现在可以fillstroke此路径,或者如果您想使用核心图形,则可以获得CGPath

有关文档,请参阅here

答案 2 :(得分:1)

如果您需要Swift 4.2同样的功能:

  func drawOldStyle() {

        guard let context = UIGraphicsGetCurrentContext() else{
            return
        }


        //Next, define the rectangle:
        let myRect = CGRect(x: 30, y: 100, width: 100, height: 20)

        //Now, set the fill color, e.g red
        context.setFillColor(UIColor.red.cgColor)

        //Set the stroke color, e.g. green:
        context.setFillColor(UIColor.green.cgColor)

        //Finally, fill the rectangle:
        context.fill( myRect)

        // AND Stroke:
        context.stroke(myRect)

    }
相关问题