UIGraphicsGetImageFromCurrentContext并保留纵横比

时间:2017-04-05 21:23:21

标签: ios swift cocoa-touch uiimageview

我正在尝试实现一个UIImageView子类,允许用户使用他们的手指在图像视图中绘制。我UIImageView的contentMode设置为Aspect Fill。我注意到,当我的绘图代码执行并且从图形上下文中提取结果图像时,它将以Scale to Fill类型格式进行缩放,这不是我想要的。我想知道是否有人知道如何提取图像并保持图像的宽高比。

class DrawImageView : UIImageView {

    var lastTouchPoint = CGPoint.zero
    var isSwiping = false

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        isSwiping = false 
        if let touchPoint = touches.first {
            lastTouchPoint = touchPoint.location(in: self)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        isSwiping = true

        if let touchPoint = touches.first {
            let currentPoint = touchPoint.location(in: self)
            UIGraphicsBeginImageContext(frame.size)

            image?.draw(in: CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height))

            if let context = UIGraphicsGetCurrentContext() {
                context.move(to: lastTouchPoint)
                context.addLine(to: currentPoint)
                context.setLineCap(CGLineCap.round)
                context.setLineWidth(9.0)
                context.setStrokeColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
                context.strokePath()
                image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                lastTouchPoint = currentPoint
            }
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        if(!isSwiping) {

            UIGraphicsBeginImageContext(frame.size)
            image?.draw(in: CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height))


            if let context = UIGraphicsGetCurrentContext() {
                context.setLineCap(CGLineCap.round)
                context.setLineWidth(9.0)
                context.setStrokeColor(red: 0/255.0, green: 0/255.0, blue: 0/255.0, alpha: 1.0)
                context.move(to: lastTouchPoint)
                context.addLine(to: lastTouchPoint)
                context.strokePath()
                image = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

使用此代码:

UIGraphicsBeginImageContext(frame.size)
image?.draw(in: CGRect(x:0, y:0, width:frame.size.width, height:frame.size.height))

你说的是“将这个完整的图像 - 无论大小或宽高比 - 绘制成宽x高的矩形。”因此,如果image的“原生”尺寸为300 x 200,而frame为200 x 200,那就是图像的绘制位置。

为避免这种情况,您需要计算要绘制的正确矩形。使用这些尺寸,您需要(对于纵横填充):

image?.draw(in: CGRect(x:-50, y:0, width:frame.size.width + 50, height:frame.size.height))

当然,您可以运行快速计算来确定实际数字,而不是硬编码值。

答案 1 :(得分:0)

我最终发现并使用提供方面填充rect和方面适合rect的函数如下:

aa = [1,2,3,2,1,3,5,3,4,8,9,7;...
      11,12,3,21,1,3,15,3,4,8,19,7;...
      21,2,3,2,1,23,5,3,34,84,9,7]';

errorbar( 1:12, mean(aa), confidence_intervals( aa, 95 ) )