Swift 绘制矩形

Swift draw rectangle

我正在尝试通过触摸绘制一个矩形。到目前为止我有两段代码,第一段是当前绘制圆的方法,第二段代码添加形状以查看,我如何改为绘制矩形?

func drawRectangle() {
    // Get the Graphics Context
    let context = UIGraphicsGetCurrentContext();

    // Set the rectangle outerline-width
    CGContextSetLineWidth(context, 5.0);

    // Set the rectangle outerline-colour
    UIColor.redColor().set()

    // Create Rectangle

    CGContextAddArc(context, (frame.size.width)/2, frame.size.height/2, (frame.size.width - 10)/2, 0.0, CGFloat(M_PI * 2.0), 1)

    // Draw
    CGContextStrokePath(context);
}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let rectangleCenter = touches.first!.locationInView(view)

    let rectangleWidth = CGFloat(50)
    let rectangleHeight = rectangleWidth

    // Create a new rectangleView
    let rectangleView = Annotations(frame: CGRectMake(rectangleCenter.x, rectangleCenter.y, rectangleWidth, rectangleHeight), shape: 1)

    view.addSubview(rectangleView)  
}

我试过以下方法:

// Create Rectangle
        CGContextAddRect(context, CGRectMake((frame.size.width)/2, frame.size.height/2, 40, 40));

它创建了矩形左上角的一部分,上面有一条线,左边有一条线。如何将其调整为完整的矩形?

我通过执行以下操作解决了我的问题:

增加这里的宽度和高度:

let rectangleWidth = CGFloat(100)
let rectangleHeight = rectangleWidth

和我的矩形方法

func drawRectangle()
    {
        // Get the Graphics Context
        let context = UIGraphicsGetCurrentContext();

        // Set the rectangle outerline-width
        CGContextSetLineWidth(context, 5.0);

        // Set the rectangle outerline-colour
        UIColor.redColor().set()

        // Create Rectangle
        CGContextAddRect(context, CGRectMake(0, 0, 100, 100));

        // Draw
        CGContextStrokePath(context);

    }

对于swift 4.2 :

此代码用于 swift 4.2

func drawRectangle()
{
    // Get the Graphics Context
    let context = UIGraphicsGetCurrentContext()

    // Set the rectangle outerline-width
    context?.setLineWidth( 5.0)

    // Set the rectangle outerline-colour
    UIColor.red.set()

    // Create Rectangle
    context?.addRect( CGRect(x: 0, y: 0, width: 100, height: 100))

    // Draw
    context?.strokePath()

}