CGContextDrawImage和Swift

时间:2015-02-10 13:20:07

标签: ios swift bitmapimage

有时CGContextDrawImage导致执行以下代码的“错误访问错误”我们无法找到原因。是否有人使用“CGContextDrawImage”遇到相同的错误?

    let bytesPerPixel = 4;
    let bytesPerRow:UInt = UInt(bytesPerPixel) * UInt(CG_Width)
    let bitsPerComponent:UInt = 8;

    let bitmapInfo = CGBitmapInfo(CGImageAlphaInfo.PremultipliedLast.rawValue)

    var pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(4)



    let context = CGBitmapContextCreate(pixel,
        UInt(CG_Width), UInt(CG_Width), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)



    let cgRect:CGRect = CGRectMake (0,0,CGFloat(CG_Width),CGFloat(CG_Width)) as CGRect



    CGContextDrawImage(context, cgRect, imageRef) 

1 个答案:

答案 0 :(得分:1)

创建像素缓冲区时,只需分配4个字节,这对于1x1位图就足够了。因为大概是CG_Width(CG_Height使用的地方?)不是1,所以当你对缓冲区的大小撒谎CGBitmapContextCreate然后进入它时,你就会在随机内存中乱涂乱画。将缓冲区分配更改为:

var pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(bytesPerRow * CG_Height)

然后更改上下文创建以使用正确的高度:

let context = CGBitmapContextCreate(pixel,
    UInt(CG_Width), UInt(CG_Height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)

如果您实际上是故意创建方形位图,请将我的CG_Height更改为CG_Width