Search code examples
swiftcore-graphics

Swift draw rectangle


I am trying to draw a rectangle on touch. So far I have two pieces of code, the fist one is a method that currently draws a circle, the 2nd piece of code adds the shape to view, how do I draw a rectangle instead?

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)  
}

I have tried the following:

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

it creates part of the top left of the rectangle with the line on top and a line down the left. How do I adjust this to be a full rectangle?


Solution

  • I was able to solve my problem by doing the following:

    increase the width and height here:

    let rectangleWidth = CGFloat(100)
    let rectangleHeight = rectangleWidth
    

    and my rectangle method

    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);
    
        }
    

    for swift 4.2 :

    this code uses for 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()
    
    }