How to procedurally draw rectangle / lines in swift using CGContext

后端 未结 3 1066
暖寄归人
暖寄归人 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 12:02

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

提交回复
热议问题