首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CGContextDrawImage与Swift

CGContextDrawImage与Swift
EN

Stack Overflow用户
提问于 2015-02-10 13:20:07
回答 1查看 1.7K关注 0票数 1

有时,CGContextDrawImage会导致“错误访问错误”,执行下面的代码,我们无法找到原因。是否有人在使用"CGContextDrawImage“时遇到过同样的错误?

代码语言:javascript
复制
    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) 
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-02-10 17:07:16

当您创建像素缓冲区时,您只分配了4个字节,这对于1x1位图来说就足够了。想必,CG_Width ( CG_Height在哪里使用?)不是1,所以当你欺骗CGBitmapContextCreate关于缓冲区的大小,然后进入它时,你在随机内存中乱写。将缓冲区分配更改为:

代码语言:javascript
复制
var pixel = UnsafeMutablePointer<CUnsignedChar>.alloc(bytesPerRow * CG_Height)

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

代码语言:javascript
复制
let context = CGBitmapContextCreate(pixel,
    UInt(CG_Width), UInt(CG_Height), bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo)

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28432736

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档