我想在一個空的 CGImage 黑色畫布上畫一些線。創建特定大小的空白 CGImage 應該是微不足道的事情,但我不能。我試過擴展 CGImage init?使用所需的資訊呼叫 self.init(width:height:...bitmapInfo:provider:...) 但我對 CGBitmapInfo 和 CGDataProvider 的了解不夠。
關于如何創建這個空畫布的任何幫助或指導?還有其他不使用 UIKit 的方法嗎?
謝謝!
uj5u.com熱心網友回復:
你不是在 aCGImage上畫,而是在 a上畫CGContext。您要做的是創建位圖背景關系,繪制到位圖背景關系中,然后從背景關系位圖緩沖區創建影像。這是我在 Playground 中輸入的示例。
匯入 UIKit
// CGContexts like rowbytes that are multiples of 16.
func goodBytesPerRow(_ width: Int) -> Int {
return (((width * 4) 15) / 16) * 16
}
func drawMyImage() -> CGImage? {
let bounds = CGRect(x: 0, y:0, width: 200, height: 200)
let intWidth = Int(ceil(bounds.width))
let intHeight = Int(ceil(bounds.height))
let bitmapContext = CGContext(data: nil,
width: intWidth, height: intHeight,
bitsPerComponent: 8,
bytesPerRow: goodBytesPerRow(intWidth),
space: CGColorSpace(name: CGColorSpace.sRGB)!,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
if let cgContext = bitmapContext {
cgContext.saveGState()
cgContext.setFillColor(gray: 0, alpha: 1.0)
cgContext.fill(bounds)
/* ... do other drawing here ... */
cgContext.restoreGState()
return cgContext.makeImage()
}
return nil
}
let image = drawMyImage()
這是使用 32 位 ARGB 值繪制的。Core Graphics 最喜歡它的行位元組是 16 的倍數(或者至少在 2006 年我寫 Quartz 2D 書時是這樣)。因此goodBytesPerRow,對于 32 位 ARGB 像素,計算給定寬度的 16 倍數的 rowBytes。
“位圖資訊”是常量的組合,決定了像素格式CGImageAlphaInfo和CGBitmapInfo. 在這種情況下,我們說我們希望首先使用 alpha 通道(因此 ARGB 而不是 RGBA),并且我們希望使用顏色通道預先乘以 alpha 值的像素。
一旦你有了位圖背景關系,你就可以畫出你喜歡的東西。你說你想在黑色背景上畫一些線條 - 所以這只是給你黑色背景,讓線條作為讀者的練習。
最后,您可以CGImage使用makeImage. 如果你想要一個UIImage,你可以用UIImage(cgImage:)
PSCGImageProvider如果您想從原始記憶體塊構造影像,或者通過從檔案或其他來源中流式傳輸資料,您將使用。它基本上告訴系統如何獲取影像資料。
在這種情況下,當我們創建位圖背景關系時,我們傳入“nil”作為要求作業系統為我們分配影像幀緩沖區的資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/332950.html
