【问题标题】:How do I rotate a CGImageRef? [duplicate]如何旋转 CGImageRef? [复制]
【发布时间】:2013-01-15 21:12:45
【问题描述】:

我有一个UIImage,当我的 iPad 纵向放置时,它的方向似乎正确,但是当我得到与之关联的 CGImageRef 时,CGImageRef 逆时针旋转了 90 度。经过一番谷歌搜索,我了解到这是因为CGImageRef 没有与UIImage 不同的方向数据。我需要查看和修改CGImageRef 中的一些像素,我目前正在通过直接访问 rawData 变量(图像是 UIImage*)来执行此操作:

CGImageRef imageRef = [image CGImage];

CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB(); //maybe make ...Gray();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpaceRef, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);

CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);

但是,为了让我正确修改存储在 rawData 中的像素数据,我需要 CGImageRef 处于正确的方向。如何将CGImageRef 顺时针旋转 90 度,然后访问 rawData(像素信息)?

【问题讨论】:

    标签: ios objective-c


    【解决方案1】:

    试试这个:

    CGImageRef imageRef = [sourceImage CGImage];
    CGColorSpaceRef colorSpaceInfo = CGImageGetColorSpace(imageRef);
    
    
    CGContextRef bitmap;
    
    if (sourceImage.imageOrientation == UIImageOrientationUp || sourceImage.imageOrientation == UIImageOrientationDown) {
        bitmap = CGBitmapContextCreate(NULL, targetWidth, targetHeight, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
    
    } else {
        bitmap = CGBitmapContextCreate(NULL, targetHeight, targetWidth, CGImageGetBitsPerComponent(imageRef), CGImageGetBytesPerRow(imageRef), colorSpaceInfo, bitmapInfo);
    
    }   
    
    if (sourceImage.imageOrientation == UIImageOrientationLeft) {
        CGContextRotateCTM (bitmap, radians(90));
        CGContextTranslateCTM (bitmap, 0, -targetHeight);
    
    } else if (sourceImage.imageOrientation == UIImageOrientationRight) {
        CGContextRotateCTM (bitmap, radians(-90));
        CGContextTranslateCTM (bitmap, -targetWidth, 0);
    
    } else if (sourceImage.imageOrientation == UIImageOrientationUp) {
        // NOTHING
    } else if (sourceImage.imageOrientation == UIImageOrientationDown) {
        CGContextTranslateCTM (bitmap, targetWidth, targetHeight);
        CGContextRotateCTM (bitmap, radians(-180.));
    }
    
    CGContextDrawImage(bitmap, CGRectMake(0, 0, targetWidth, targetHeight), imageRef);
    CGImageRef ref = CGBitmapContextCreateImage(bitmap);
    

    【讨论】:

    • 为什么左右方向需要翻转目标高度和宽度?还有,为什么要翻译位图?
    • 位图信息从何而来?您可能也应该释放 CGContextRef。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 1970-01-01
    • 2022-08-16
    • 2011-12-20
    相关资源
    最近更新 更多