CGContextDrawImage 和 Swift

CGContextDrawImage and Swift

有时 CGContextDrawImage 导致 "bad access error" 执行以下代码我们无法找到原因。有没有人在使用 "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) 

当您创建像素缓冲区时,您只分配了 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