You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

iOS开发:ImageView绘图线条模糊生硬问题求助

解决ImageView绘图线条模糊生硬的问题

嘿,我帮你搞定这个绘图模糊的问题!你的核心问题主要出在没有适配Retina屏幕的分辨率以及坐标坐标系不匹配上,这两个点是导致线条模糊、位置不对的关键。下面是具体的修复方案:

问题分析

  1. Retina屏幕适配缺失:你用的UIGraphicsBeginImageContext是旧的方法,它默认使用1倍缩放,在高分辨率的Retina屏幕上,绘制的图像会被拉伸,自然就模糊了。
  2. 坐标系不匹配:你获取触摸坐标时用的是self.view的坐标系,但绘图是在imageView上进行的,如果imageView不是铺满整个view,坐标就会错位,线条也会显得生硬。

具体修复步骤

1. 替换图像上下文创建方法

把drawLines里的UIGraphicsBeginImageContext换成支持缩放的UIGraphicsBeginImageContextWithOptions,并传入屏幕的缩放因子:

func drawLines(fromPoint:CGPoint,toPoint:CGPoint) {
    // 用imageView的bounds尺寸,传入屏幕scale适配Retina
    UIGraphicsBeginImageContextWithOptions(self.imageView.bounds.size, false, UIScreen.main.scale)
    // 绘制时匹配imageView的bounds,而不是view的frame
    imageView.image?.draw(in: self.imageView.bounds)
    
    let context = UIGraphicsGetCurrentContext()
    context?.move(to: fromPoint)
    context?.addLine(to: toPoint)
    
    context?.setBlendMode(isDrawing ? .normal : .clear)
    tool.center = toPoint
    
    context?.setLineCap(.round)
    context?.setLineWidth(lw)
    context?.setStrokeColor(UIColor(red: red, green: green, blue: blue, alpha: alpha).cgColor)
    context?.strokePath()
    
    imageView.image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
}

2. 修正触摸坐标的坐标系

把触摸事件中的坐标从self.view转换到imageView的坐标系下,确保触摸点和绘图位置完全对应:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = false
    if let touch = touches.first {
        // 获取相对于imageView的精确坐标
        lastPoint = touch.preciseLocation(in: self.imageView)
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    swiped = true
    if let touch = touches.first {
        let currentPoint = touch.preciseLocation(in: self.imageView)
        drawLines(fromPoint: lastPoint, toPoint: currentPoint)
        lastPoint = currentPoint
    }
}

3. 优化橡皮擦逻辑(可选)

你原来用白色模拟橡皮擦的方式在某些场景下可能会有问题,现在用CGBlendMode.clear的方式更准确,你的代码里已经有这个判断,但可以简化一下颜色设置:

@IBAction func eraser(_ sender: AnyObject) {
    if (isDrawing) {
        // 橡皮擦模式下用clear混合模式,不需要设置颜色
        tool.image = #imageLiteral(resourceName: "eraser2")
        toolicon.setImage(#imageLiteral(resourceName: "pen"), for: .normal)
        lw = 50
    } else {
        (red,green,blue) = (0,0,0)
        tool.image = #imageLiteral(resourceName: "blank")
        toolicon.setImage(#imageLiteral(resourceName: "eraser"), for: .normal)
        lw = 2.5
    }
    isDrawing = !isDrawing
}

修复后的效果

经过这些修改,你的绘图线条会清晰很多,因为上下文现在和屏幕分辨率一致,同时触摸坐标和绘图区域完全匹配,线条也会更流畅自然。

内容的提问来源于stack exchange,提问作者lowe493

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:42:48