[英]how to create an image from matrix of colours in swift?
我必須從顏色矩陣創建圖像。 顏色以十六進制表示。 例:
[ffffff 000000 000000 ffffff 000000 ffffff 000000 ffffff 000000]
我有以下代碼:
struct Matrix
{
let rows: Int, columns: Int
var grid: [String]
init (rows: Int, columns: Int)
{
self.rows = rows
self.columns = columns
grid = Array(count: rows * columns, repeatedValue: "")
}
func indexIsValidForRow(row: Int, column: Int) -> Bool
{
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> String
{
get {
assert(indexIsValidForRow(row, column: column), "Index out range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValidForRow(row, column: column), "Index out range")
grid[(row * columns) + column] = newValue
}
}
}
var matrix = Matrix(rows: 512, columns: 512) //After this line I will add the colours in this matrix
謝謝
您可以嘗試使用CGBitmapContextCreate()創建位圖,使用數據填充它,然后創建UIImage,如下所示:
CGContextRef bitmap = CGBitmapContextCreate(...);
// populate bitmap with data
// create UIImage from bitmap
CGImageRef imageRef = CGBitmapContextCreateImage(bitmap);
UIImage *image = [UIImage imageWithCGImage:imageRef];
// release resources
CGContextRelease(bitmap);
CGImageRelease(imageRef);
位圖格式以及如何填充取決於原始數據。
更新#1
var matrix = Matrix(rows: 64, columns: 64) // After this line I will add the colours in this matrix
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue) | CGBitmapInfo.ByteOrder32Little;
var bitmap = CGBitmapContextCreate(nil, matrix.columns, matrix.rows, 8, 0, colorSpace, bitmapInfo)
var bitmapData = UnsafeMutablePointer<UInt32>(CGBitmapContextGetData(bitmap))
for var i = 0; i < matrix.rows; i++
{
for var j = 0; j < matrix.columns; j++
{
// constant used with format RGBA
bitmapData[matrix.rows * i + j] = 0x00ff00ff
}
}
let imageRef = CGBitmapContextCreateImage(bitmap)
let image = UIImage(CGImage: imageRef)
由於字符串值,當前的實現很難使用。 您需要為矩陣使用整數值,例如UInt32
。 在我的示例中,我為顏色使用恆定值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.