[6/3a1b] UIImage的Orientation

UIImage内部应该是以CGImageRef的方式进行存储的,而且无论你是竖向摄影还是横向摄影,最后储存的时候其实都是横向的,也就是UIImageOrientationUp的方式,然后以指定不同的UIImageOrientation的取值来确定显示的时候的方向。这样一来对于UIImageView,不管你是如何来take的这个photo,都可以以正确的方向显示这个Image。

这样一来当使用

CGImageCreateWithImageInRect

的时候,如果你的图片是UIImageOrientationLeft或者UIImageOrientationRight的时候,你所使用的长和宽必须互换,原因是其中的CGImageRef是横向存储的。

[UIImageInstance CGImage]的时候,UIImageOrientation的信息会丢失,所以一定要提前进行纪录,然后

在使用[UIImage imageWithCGImage: scale: orientation:]再次提供,进行存储。

我估计其中的scale信息实际上也是UIImage和CGImageRef的区别,这也就是为什么苹果要提供这个API的原因

以下是一个crop UIImage称为一个正方形的代码

//crop a rectangle into a maxium square in it
+(UIImage*)cropIntoSquareFromImage:(UIImage*)image{
    UIImage* squareImage;
    CGFloat inputImageWidth;
    CGFloat inputImageHeight;
    CGFloat inputImageOrientation=image.imageOrientation;
    if (inputImageOrientation==UIImageOrientationLeft||inputImageOrientation==UIImageOrientationRight) {
        inputImageWidth=image.size.height;
        inputImageHeight=image.size.width;
    }else{
    inputImageHeight=image.size.height;
    inputImageWidth=image.size.width;
    }
    CGRect cropRect;
    CGRect intCropRect;
    //crop image within center
    if (inputImageHeight>=inputImageWidth) {
        cropRect=CGRectMake(0,(inputImageHeight-inputImageWidth)/2, inputImageWidth, inputImageWidth);
    }else{
        cropRect=CGRectMake((inputImageWidth-inputImageHeight)/2, 0, inputImageHeight, inputImageHeight);
    }
    intCropRect=CGRectIntegral(cropRect);
    
    CGImageRef cropImageRef=CGImageCreateWithImageInRect([image CGImage], intCropRect);
    
    if (inputImageOrientation==UIImageOrientationLeft) {
        squareImage= [[UIImage alloc] initWithCGImage:cropImageRef scale:[FZDataImageController screenScale] orientation:UIImageOrientationLeft];
    }else if (inputImageOrientation==UIImageOrientationRight)
    {
        squareImage= [[UIImage alloc] initWithCGImage:cropImageRef scale:[FZDataImageController screenScale] orientation:UIImageOrientationRight];
    }else if (inputImageOrientation==UIImageOrientationDown)
    {
         squareImage= [[UIImage alloc] initWithCGImage:cropImageRef scale:[FZDataImageController screenScale] orientation:UIImageOrientationDown];
    }else{
    squareImage= [[UIImage alloc] initWithCGImage:cropImageRef];
    }

    CFRelease(cropImageRef);
    return squareImage;
}
posted @ 2012-08-31 02:25  淡引  阅读(981)  评论(0编辑  收藏  举报