在iPhone中绘制并填充矩形

在iPhone中绘制并填充矩形,iphone,core-graphics,Iphone,Core Graphics,我有4个点,比如(x1,y1),(x2,y2),(x2,y3)和(x4,y4)。我需要用这些点画一个矩形,并在矩形内填充一种颜色。有人能帮我吗 创建一个UIBezierPath对象。移动到第一个点,然后调用addLineToPoint:获取后续三个点。然后调用closePath 您现在可以fill或stroke此路径,或者如果要使用核心图形,可以获得CGPath 有关文档,请参阅。首先,获取当前图形上下文: CGContextRef context = UIGraphicsGetCurrentC

我有4个点,比如(x1,y1),(x2,y2),(x2,y3)和(x4,y4)。我需要用这些点画一个矩形,并在矩形内填充一种颜色。有人能帮我吗

创建一个
UIBezierPath
对象。移动到第一个点,然后调用
addLineToPoint:
获取后续三个点。然后调用
closePath

您现在可以
fill
stroke
此路径,或者如果要使用核心图形,可以获得
CGPath


有关文档,请参阅。

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

CGContextRef context = UIGraphicsGetCurrentContext();
接下来,定义矩形:

CGRect myRect = {x1, y1, x2 - x1, y2 - y1};
CGContextFillRect(context, myRect);
现在,设置填充颜色,例如红色

CGContextSetRGBFillColor(context, 1.0, 0.0, 0.0, 1.0);
设置笔划颜色,例如绿色:

CGContextSetRGBStrokeColor(context, 0.0, 1.0, 0.0, 1.0);
最后,填充矩形:

CGRect myRect = {x1, y1, x2 - x1, y2 - y1};
CGContextFillRect(context, myRect);

如果您在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)

    }

今天有两张反对票。没有提供评论。有什么想法吗?哇,这个答案又投了两张反对票,还是没有评论。没有勇气提供反馈?
CGContextFillRect
不会绘制边框,您还需要添加一个
CGContextStrokeRect