gpt4 book ai didi

ios - CGContext 初始化后不绘制

转载 作者:行者123 更新时间:2023-12-01 19:33:13 27 4
gpt4 key购买 nike

我正在尝试在 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)
}

并且 View 没有在显示上勾勒出来,而使用当前上下文可以自然地工作(显示边界边框笔划):

    override func draw(_ rect: CGRect) {
guard let ctx = UIGraphicsGetCurrentContext() else {
return
}
ctx.setStrokeColor(UIColor.orange.cgColor)
ctx.setLineWidth(3.0)
ctx.stroke(rect)
}

我已经按照 CGContext init 方法的 swift 头文件中的描述进行了操作。这是什么原因与获取当前上下文的功能不同,因为我似乎使用了当前 View 中的位图信息集。

最佳答案

这是一个创建屏幕外内容的简单演示,用于准备某些东西(可能很重,所以不会阻塞 UI)以呈现在 View 中

demo

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
}

关于ios - CGContext 初始化后不绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61179237/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com