感谢您的宝贵时间。
在我点击图像之前图像很好,然后在我点击图像后压缩图像。
这是我的代码:
我没有使用 Storyboard ,所以我使用代码创建所有内容,这里是 ImageView。我还用代码添加了约束。
let imageEditingView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
return imageView
}()
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.first != nil {
lastPoint = (touches.first?.location(in: imageEditingView))!
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if touches.first != nil {
let currentPoint = touches.first?.location(in: imageEditingView)
drawLines(fromPoint: lastPoint, toPoint: currentPoint!)
lastPoint = currentPoint!
drawLines(fromPoint: lastPoint, toPoint: lastPoint)
}
}
func drawLines(fromPoint: CGPoint, toPoint: CGPoint) {
UIGraphicsBeginImageContext(imageEditingView.frame.size)
imageEditingView.image?.draw(in: CGRect(x: 0, y: 0, width: imageEditingView.frame.width, height: imageEditingView.frame.height))
let context = UIGraphicsGetCurrentContext()
context?.move(to: CGPoint(x: fromPoint.x, y: fromPoint.y))
context?.addLine(to: CGPoint(x: toPoint.x, y: toPoint.y))
context?.setBlendMode(CGBlendMode.normal)
context?.setLineCap(CGLineCap.round)
context?.setLineWidth(CGFloat(Int(120 * lineWidthSliderView.value)))
context?.setStrokeColor(red: red / 255, green: green / 255, blue: blue / 255, alpha: 0.01)
context?.strokePath()
imageEditingView.image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
}
Best Answer-推荐答案 strong>
我不知道您所说的“压缩”是什么意思,但我猜图像会以某种方式损坏,因为当您将图像转换为 CGContext 并返回图像时,一些数据会丢失.
我不知道如何解决这个问题,但我可以通过将 CAShapeLayer 作为子层添加到 UIImageView 并绘制你想要的东西来解决这个问题以 CGPath 的形式出现。语法与您现在使用的非常相似,唯一可能不支持的效果是混合模式,但您可以使用具有较低 alpha 值的另一个图层重新创建它。
这就是它的样子。
var drawingLayer = CAShapeLayer()
func drawLines(fromPoint: CGPoint, toPoint: CGPoint) {
let mutable = CGMutablePath()
mutable.move(to: fromPoint)
mutable.addline(to: toPoint)
drawingLayer.path = mutable
drawingLayer.fillColor = nil
drawingLayer.lineCap = kCALineCapRound
drawingLayer.lineCap = 120 * CGFloat(lineWidthSliderView.value)
//the bit in your code translated the whole thing to Int before translating it to a
//CGFloat, this is a bad idea since Ints cannot store decimals, so if there is no
//direct conversion, convert it to Double or Float
drawingLayer.strokeColor = UIColor(calibratedRed: red/255, green: green/255, blue: blue/255 , alpha: 1).cgColor
}
您还需要在某个地方执行 imageEditingView.addSubLayer(drawingLayer)
另外,当您在 context.move(to 和其他地方...
关于ios - 在图像上绘制内容后,我的 ImageView 内容模式停止工作,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/40568849/
|