ios 在 UIView 中绘画如何更改背景颜色?

问题描述

我想用手指在 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,我会得到下一个结果(白色背景丢失)

enter image description here

我尝试了 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
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...