我正在尝试在UIView draw(_ :)中创建自己的CGContext。在这里:
override func draw(_ rect: CGRect) {
//let ctx = UIGraphicsGetCurrentContext()
let width = Int(rect.size.width)
let height = Int(rect.size.height)
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * width
let data = UnsafeMutableRawPointer.allocate(byteCount: bytesPerRow * height/*727080*/, alignment: 8)
let colorSpace = CGColorSpaceCreateDeviceRGB()
guard let ctx = CGContext(data: data, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else {
return
}
ctx.setStrokeColor(UIColor.orange.cgColor)
ctx.setLineWidth(3.0)
ctx.stroke(rect)
}
并且视图未在显示中显示轮廓,而使用当前上下文很自然(显示边界笔触):
override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
ctx.setStrokeColor(UIColor.orange.cgColor)
ctx.setLineWidth(3.0)
ctx.stroke(rect)
}
我遵循了svift头文件中CGContext init方法的描述。是什么原因导致此功能与获取当前上下文不同,因为我似乎使用了当前视图中的位图信息集。
这里是创建屏幕外内容以准备要显示的某些内容(可能很沉重,因此不会阻塞UI)的简单演示
class ViewWithOffscreenDrawing: UIView {
private var offscreenImage: CGImage? = nil
override func draw(_ rect: CGRect) {
if offscreenImage == nil { // image not ready
DispatchQueue.global(qos: .background).async { // draw offscreen
let image = renderSomething(of: rect.size)
DispatchQueue.main.async { [weak self] in
self?.offscreenImage = image
self?.setNeedsDisplay()
}
}
return
}
// image has prepared - just draw on screen
UIGraphicsGetCurrentContext()?.draw(offscreenImage!, in: rect)
}
}
func renderSomething(of size: CGSize) -> CGImage? {
let bitsPerComponent = 8
let bytesPerRow = Int(size.width) * 4
let colorSpace = CGColorSpace(name: CGColorSpace.genericRGBLinear)!
let context = CGContext(data: nil, width: Int(size.width), height: Int(size.height),
bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow,
space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
// >>> draw anything heavy in background context
context?.setFillColor(gray: 1, alpha: 1)
context?.fill(CGRect(origin: .zero, size: size))
context?.setFillColor(UIColor.red.cgColor)
context?.fillEllipse(in: CGRect(origin: .zero, size: size))
// <<<
return context?.makeImage() // generated result
}