代码之家  ›  专栏  ›  技术社区  ›  Bob

重绘时未清除UIBezierPath

  •  0
  • Bob  · 技术社区  · 7 年前

    我有自己的习惯 UIView 在其中我画了一个UIBezierPath。此视图用于UITableViewCell。所以当我滚动时,自定义视图的bezier路径会被重新绘制。问题是新路径会覆盖旧的路径图(上下文没有正确清除)。我打电话来 setNeedsDisplay() 在桌子上,我也把 clearsContextBeforeDrawing = true context.clear(rect) 但这一点都不理想,因为我失去了背景(它变成黑色)。

    有没有办法解决这个问题?

    class CustomView: UIView {
    
    var percentage: CGFloat = 0 {
        didSet {
            setNeedsDisplay()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        clearsContextBeforeDrawing = true
        contentMode = .redraw
        clipsToBounds = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func draw(_ rect: CGRect) {
        super.draw(rect)
    
        // NOTE: don't really like doing this
        let context = UIGraphicsGetCurrentContext()!
        context.clear(rect)
    
        let center = CGPoint(x: self.bounds.size.width/2, y: self.bounds.size.height/2)
    
        let path = UIBezierPath(arcCenter: center,
                                radius: self.bounds.size.width/2-10,
                                startAngle: 0.5 * .pi,
                                endAngle: (-2.0 * self.percentage + 0.5) * .pi,
                                clockwise: false)
    
        path.lineWidth = 4
        UIColor.red.setStroke()
        path.stroke()
    }
    }
    

    这是设置我的单元格和自定义uiview的地方。

    override func tableView(_ tableView: UITableView, cellForItemAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
            let num = list[indexPath.item]
            let percentage = CGFloat(num) / 10
            cell.customView.percentage = percentage // Custom view should get redrawn after this call
            return cell
        }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   matt    7 年前

    我认为问题仅仅是你的画太大了,偏离了单元格的范围,因为你的视图没有剪裁到边界。那是不连贯的。每个单元格只需要绘制自己的内容。

    细胞 绘图。你正在用你的画感染邻近的细胞。

    顺便说一下,你说:

    但这一点都不理想,因为我失去了背景(它变成黑色)。”

    self.backgroundColor = .clear 在你的 init .