2

谢谢你的时间。

在我点击图像之前图像很好,然后在我点击图像后压缩图像。

这是我的代码:

我没有使用故事板,所以我用代码创建了所有东西,这里是 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()
}    
4

1 回答 1

0

我不知道您所说的“压缩”是什么意思,但我猜图像会以某种方式损坏,因为当您将图像转换CGContext回图像时会丢失一些数据。

我不知道如何解决这个问题,但我会通过将 aCAShapeLayer作为子层添加到 中来解决这个问题,并以 aUIImageView的形式在那里绘制你想要的东西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)

另外,当您在其他地方进行转换时,您不需要将 CGPoint 转换为另一个 CGPoint context.move(to:)...

于 2016-11-13T01:29:01.913 回答