How to procedurally draw rectangle / lines in swift using CGContext

后端 未结 3 1057
暖寄归人
暖寄归人 2021-01-31 11:22

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 overri

3条回答
  •  醉梦人生
    2021-01-31 11:58

    An updated answer using Swift 3.0

    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: CGPoint.zero, size: size)
        let opaque = false
        let scale: CGFloat = 0
        UIGraphicsBeginImageContextWithOptions(size, opaque, scale)
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
    
        // Setup complete, do drawing here
        context.setStrokeColor(UIColor.red.cgColor)
        context.setLineWidth(5.0)
    
        // Would draw a border around the rectangle
        // context.stroke(bounds)
    
        context.beginPath()
        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
    }
    
    let imageSize = CGSize(width: 200, height: 200)
    let imageView = UIImageView(frame: CGRect(origin: CGPoint(x: 100, y: 100), size: imageSize))
    let image = drawCustomImage(size: imageSize)
    imageView.image = image
    

提交回复
热议问题