繁体   English   中英

在UIScrollView中的UIImageView上绘图

[英]Drawing on UIImageView within UIScrollView

关于我的应用程序:用户可以在UIWebView查看PDF文件。 我有一个选项供用户选择是否要滚动pdf或在其上做笔记。 当他们做笔记时,滚动被禁用,反之亦然。 但是,当用户绘图时,线条会向上移动并变得朦胧,如下所示: 图片 (红色框是pdf中的文字)

这是我的代码:

在笔和滚动之间切换:

var usingPen = false
@IBAction func usePen(sender: AnyObject) {

    usingPen = true
    webView.userInteractionEnabled = false
    UIView.animateWithDuration(0.3) { () -> Void in
        self.popUpView.alpha = 0
    }

}

@IBAction func useScroll(sender: AnyObject) {

    usingPen = false
    webView.userInteractionEnabled = true
    UIView.animateWithDuration(0.3) { () -> Void in
        self.popUpView.alpha = 0
    }

}

用户绘制的objectViewobjectView ):

var objectView = UIImageView()
override func viewDidAppear(animated: Bool) {

    objectView.frame.size = webView.scrollView.contentSize
    webView.scrollView.addSubview(objectView)

}

在图像视图上绘图:

var start = CGPoint()

let size: CGFloat = 3

var color = UIColor.blackColor()

func draw(start: CGPoint, end: CGPoint) {

    if usingPen == true {

        UIGraphicsBeginImageContext(self.objectView.frame.size)
        let context = UIGraphicsGetCurrentContext()
        objectView.image?.drawInRect(CGRect(x: 0, y: 0, width: objectView.frame.width, height: objectView.frame.height))
        CGContextSetFillColorWithColor(context, color.CGColor)
        CGContextSetStrokeColorWithColor(context, color.CGColor)
        CGContextSetLineWidth(context, size)
        CGContextBeginPath(context)
        CGContextMoveToPoint(context, start.x, start.y)
        CGContextAddLineToPoint(context, end.x, end.y)
        CGContextStrokePath(context)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        objectView.image = newImage

    }


}

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

    start = (touches.first?.locationInView(self.objectView))!

}

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

    draw(start, end: (touches.first?.locationInView(self.objectView))!)
    start = (touches.first?.locationInView(self.objectView))!

}

如何防止图形模糊和移动? 谢谢你的帮助。

这可能是由于图像缩放问题引起的。 由于您要绘制的图像的缩放比例为1(默认设置),并且屏幕的缩放比例为2或3,因此每次复制和绘制线条时,线条都会继续略微模糊。 解决方案是在创建图像上下文时指定屏幕的缩放比例:

UIGraphicsBeginImageContextWithOptions(self.objectView.frame.size, false, UIScreen.mainScreen().scale)

请注意,绘制线条的方式效率很低。 相反,您可能想要创建一个CGBitmapContext并不断地对其进行绘制。 这样会更快,并且还可以消除您遇到的“发电损失”问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM