How do I draw on an image in Swift?

前端 未结 5 1543
深忆病人
深忆病人 2020-12-09 04:18

I need to be able to programmatically draw on an image, and save that image for later use. Say, draw a line on specific x and y coordinates on the image, save the image, and

5条回答
  •  忘掉有多难
    2020-12-09 04:47

    Since iOS 10 you can use the UIGraphicImageRenderer, which has a better syntax and has some great features!

    Swift 4

    let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
    let image = renderer.image { context in
        // draw your image into your view
        context.cgContext.draw(UIImage(named: "myImage")!.cgImage!, in: view.frame)
        // draw even more...
        context.cgContext.setFillColor(UIColor.red.cgColor)
        context.cgContext.setStrokeColor(UIColor.black.cgColor)
        context.cgContext.setLineWidth(10)
        context.cgContext.addRect(view.frame)
        context.cgContext.drawPath(using: .fillStroke)
    }
    

提交回复
热议问题