我已经看到了一些在UIImage之上绘图的例子,我认为我已经完全遵循了代码,但它似乎并没有为我工作。谁能发现我出错的地方?此代码位于按钮的动作功能中。保存的两个图像是相同的。我原以为其中一个人画了一条白线。谢谢。代码:
UIGraphicsBeginImageContext((uiImage?.size)!)
uiImage?.draw(at: CGPoint(x:0,y:0))
let newContext = UIGraphicsGetCurrentContext()!
newContext.setLineWidth(2)
newContext.move(to: CGPoint(x:10,y:10))
newContext.addLine(to: CGPoint(x:150,y:150))
newContext.setStrokeColor(UIColor.white.cgColor)
newContext.strokePath()
finalImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(uiImage!, nil, nil, nil)
UIImageWriteToSavedPhotosAlbum(finalImage!, nil, nil, nil)
答案 0 :(得分:0)
您可能正在使用不正确的UIGraphics。你似乎在使用:
finalImage = UIGraphicsGetImageFromCurrentContext()
您可能想尝试:
finalImage = UIGraphicsGetImageFromCurrentImageContext()
您可能还想调用之前调用UIGraphicsEndImageContext()
这些方法。确保这是最后一行
修改强> 这是我的绘图和保存图像的代码。希望这会有所帮助。
var imageToSave: UIImage? {
didSet {
UIImageWriteToSavedPhotosAlbum(imageToSave, nil, nil, nil)
}
}
func drawLine(from fromPoint: CGPoint, to toPoint: CGPoint) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, 0)
backgroundImageView.image?.draw(in: view.bounds)
let drawContext = UIGraphicsGetCurrentContext()
drawContext?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
drawContext?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
drawContext?.setLineCap(CGLineCap.round)
drawContext?.setLineWidth(brushWidth)
drawContext?.setStrokeColor(color.cgColor)
drawContext?.setBlendMode(CGBlendMode.normal)
drawContext?.strokePath()
imageToSave = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}