ios 在 UIView 中绘制。如何改变背景颜色?

ios painting inside UIView. How change background color?

我想用手指在里面作画UIView。我正在使用绘图功能:

override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }
    draw(inContext: context)
}

func draw(inContext context: CGContext) {
    
    // 2
    context.setLineWidth(5)

    context.setStrokeColor(UIColor.black.cgColor)
    context.setLineCap(.round)
    //context.setFillColor(UIColor.white.cgColor)

    // 3
    for line in lineArray {
        
        // 4
        guard let firstPoint = line.first else { continue }
        context.beginPath()
        context.move(to: firstPoint)
        
        // 5
        for point in line.dropFirst() {
            context.addLine(to: point)
        }
        context.strokePath()
    }
}

对于导出,我使用此代码:

func exportDrawing() -> UIImage? {

    // 2
    UIGraphicsBeginImageContext(frame.size)
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    
    // 3         
    draw(inContext: context)
    
    // 4
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

用户画的线就可以了。但是导出时我不能保持白色背景UIImage。例如,如果我尝试将绘画结果保存到其他 ImageView,我会得到下一个结果(白色背景丢失)

我试过 context.setFillColor(UIColor.white.cgColor) 但没用。 我该如何解决?

将您的自定义函数更改为:

func draw(inContext context: CGContext, rect: CGRect, bkgColor: UIColor?) {
        
    // if a background color was passed, fill the background
    if let c = bkgColor {
        context.setFillColor(c.cgColor)
        context.fill(rect)
    }
        
    // 2
    context.setLineWidth(5)

    context.setStrokeColor(UIColor.black.cgColor)
    context.setLineCap(.round)
    //context.setFillColor(UIColor.white.cgColor)

    // 3
    for line in lineArray {
        
        // 4
        guard let firstPoint = line.first else { continue }
        context.beginPath()
        context.move(to: firstPoint)
        
        // 5
        for point in line.dropFirst() {
            context.addLine(to: point)
        }
        context.strokePath()
    }
}

并更改您的调用:

override func draw(_ rect: CGRect) {
    guard let context = UIGraphicsGetCurrentContext() else { return }
    //draw(inContext: context)
    draw(inContext: context, rect: rect, bkgColor: nil)
}

和:

func exportDrawing() -> UIImage? {

    // 2
    UIGraphicsBeginImageContext(frame.size)
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    
    // 3         
    //draw(inContext: context)
    draw(inContext: context, rect: CGRect(origin: .zero, size: frame.size), bkgColor: .white)
    
    // 4
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}