如何用swift中的颜色矩阵创建图像?

时间:2015-07-30 15:12:09

标签: ios image 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    

谢谢

1 个答案:

答案 0 :(得分:1)

您可以尝试使用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。在我的例子中,我使用常量值来表示颜色。