我想用手指在 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)
,但没有奏效。
我该如何解决?
答案 0 :(得分:2)
将您的自定义函数更改为:
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
}