为什么我不能在 UIImage 上绘图?

Why can't I draw on top of a UIImage?

我看过几个在 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)

您可能使用了不正确的 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()
}