如何使这个签名视图更清晰,更少模糊?

时间:2017-11-08 11:25:24

标签: ios swift xcode core-graphics

如何在用户绘制时使此签名视图具有最佳清晰度。我使用此代码使用CoreGraphics在图像上绘制。目前它就像这样,我想要另一个。帮助我。以下是代码段。

我正在获得此链接的图片

Have This

我希望图片更清晰,就像这个链接

Want this

var lastPoint:CGPoint!
var isSwiping:Bool!
var isEditedImage = false
var lineWidth:CGFloat = 3.0
var lineOpacity:CGFloat = 1.0
var lineColor = UIColor.black

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

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

    isSwiping = true
    if let touch = touches.first{
        let currentPoint = touch.location(in: signView)
        UIGraphicsBeginImageContext(self.signView.frame.size)
        self.signView.image?.draw(in: CGRect(x: 0, y: 0, width: self.signView.frame.size.width, height: self.signView.frame.size.height))
        UIGraphicsGetCurrentContext()?.move(to: CGPoint(x: lastPoint.x, y: lastPoint.y))
        UIGraphicsGetCurrentContext()?.addLine(to: CGPoint(x: currentPoint.x, y: currentPoint.y))
        UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)
        UIGraphicsGetCurrentContext()?.setLineWidth(lineWidth)
        UIGraphicsGetCurrentContext()?.setAlpha(lineOpacity)
        UIGraphicsGetCurrentContext()?.setStrokeColor(lineColor.cgColor)
        UIGraphicsGetCurrentContext()?.beginTransparencyLayer(auxiliaryInfo: nil)
        UIGraphicsGetCurrentContext()?.strokePath()
        UIGraphicsGetCurrentContext()?.endTransparencyLayer()
        self.signView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        lastPoint = currentPoint
        isEditedImage = true
    }
}

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

    if(!isSwiping) {
        // This is a single touch, draw a point
        UIGraphicsBeginImageContext(self.signView.frame.size)
        self.signView.image?.draw(in: CGRect(x: 0, y: 0, width: self.signView.frame.size.width, height: self.signView.frame.size.height))
        UIGraphicsGetCurrentContext()?.setLineCap(CGLineCap.round)
        UIGraphicsGetCurrentContext()?.setLineWidth(lineWidth)
        UIGraphicsGetCurrentContext()?.setAlpha(lineOpacity)
        UIGraphicsGetCurrentContext()?.setStrokeColor(lineColor.cgColor)
        UIGraphicsGetCurrentContext()?.beginTransparencyLayer(auxiliaryInfo: nil)
        UIGraphicsGetCurrentContext()?.strokePath()
        UIGraphicsGetCurrentContext()?.endTransparencyLayer()
        self.signView.image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
    }
}

1 个答案:

答案 0 :(得分:0)

图形上下文中的细节量(相对于像素化)取决于上下文的scale。您错误地调用UIGraphicsBeginImageContext,因此您未能提供比例。始终致电UIGraphicsBeginImageContextWithOptions,以便提供更高的比例。 (但是,不要让它太高;更高规模的上下文需要指数级的内存。)