在iPhone上绘制并填充一个矩形

3

我有四个点,分别是(x1,y1), (x2,y2), (x2,y3)和(x4,y4)。我需要用这些点画一个矩形,并在矩形内填充颜色。请问有人可以帮我吗?

3个回答

24

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

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
今天有两个踩票,没有提供任何评论。有什么想法吗? - Max MacLeod
2
哇,这个回答又被踩了两次,还是没有评论。不够勇敢提供反馈吗? - Max MacLeod
2
CGContextFillRect 不会绘制边框,您还需要添加 CGContextStrokeRect - Gianluca P.

2
创建一个 UIBezierPath 对象。移动到第一个点,然后对于你的下一个三个点调用 addLineToPoint: 方法。最后调用 closePath 方法。
现在,您可以使用 fillstroke 此路径,或者如果要使用核心图形,则可以获取 CGPath
参见此处进行文档查询。

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)

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接