gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:50:04 24 4
gpt4 key购买 nike

我看过一些在 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()
}

关于ios - 为什么我不能在 UIImage 上绘图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48424173/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com