How to procedurally draw rectangle / lines in swift using CGContext

iphaaw picture iphaaw · Aug 10, 2014 · Viewed 38.7k times · Source

I've been trawling the internet for days trying to find the simplest code examples on how to draw a rectangle or lines procedurally in Swift. I have seen how to do it by overriding the DrawRect command. I believe you can create a CGContext and then drawing into an image, but I'd love to see some simple code examples. Or is this a terrible approach? Thanks.

class MenuController: UIViewController 
{

    override func viewDidLoad() 
    {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.backgroundColor = UIColor.blackColor()

        var logoFrame = CGRectMake(0,0,118,40)
        var imageView = UIImageView(frame: logoFrame)
        imageView.image = UIImage(named:"Logo")
        self.view.addSubview(imageView)

        //need to draw a rectangle here
    }
}

Answer

Wolf McNally picture Wolf McNally · Aug 10, 2014

Here's an example that creates a custom UIImage containing a transparent background and a red rectangle with lines crossing diagonally through it.

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad();

        let imageSize = CGSize(width: 200, height: 200)
        let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 100, y: 100), size: imageSize))
        self.view.addSubview(imageView)
        let image = drawCustomImage(size: imageSize)
        imageView.image = image
    }
}

func drawCustomImage(size: CGSize) -> UIImage {
    // Setup our context
    let bounds = CGRect(origin: .zero, size: size)
    let opaque = false
    let scale: CGFloat = 0
    UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
    let context = UIGraphicsGetCurrentContext()!

    // Setup complete, do drawing here
    context.setStrokeColor(UIColor.red.cgColor)
    context.setLineWidth(2)

    context.stroke(bounds)

    context.beginPath()
    context.move(to: CGPoint(x: bounds.minX, y: bounds.minY))
    context.addLine(to: CGPoint(x: bounds.maxX, y: bounds.maxY))
    context.move(to: CGPoint(x: bounds.maxX, y: bounds.minY))
    context.addLine(to: CGPoint(x: bounds.minX, y: bounds.maxY))
    context.strokePath()

    // Drawing complete, retrieve the finished image and cleanup
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}