在UIScrollView

时间:2016-02-15 20:00:17

标签: ios swift uiscrollview uiimageview drawing

关于我的应用:用户可以在UIWebView内查看PDF文件。我有一个选项供用户选择是否要滚动pdf或记录它。当他们做笔记时,滚动被禁用,反之亦然。但是,当用户绘图时,线条向上移动并变得模糊,如图所示: The pic (红色框是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
    }

}

用户使用的imageView(objectView):

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 个答案:

答案 0 :(得分:0)

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

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

请注意,您绘制线条的方式效率很低。相反,您可能想要创建一个CGBitmapContext并不断绘制到那个;它会更快,并且还可以消除&#34;代损失&#34;你有问题。