缩放图像

时间:2010-10-11 15:29:51

标签: iphone

我需要在UIImage上执行缩放操作,以下是相同的代码。导致内存泄漏。无法调试这里出错的地方。

UIImage* ScaleImageWithWH(UIImage* image, CGRect aRect) 
{
    int kMaxResolution = 1800; 

    int x;
    int y;

    x = ( image.size.width * aRect.origin.x ) / aRect.size.width;
    y = ( image.size.height * aRect.origin.y ) / aRect.size.height;

    CGImageRef imgRef =  CGImageCreateWithImageInRect (image.CGImage, CGRectMake (x,y,aRect.size.width,aRect.size.height));
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTransform transform = CGAffineTransformIdentity;

    CGRect bounds = CGRectMake(aRect.origin.x, aRect.origin.y, width, height);

    bounds.size.width = aRect.size.width;
    bounds.size.height = aRect.size.height;

    CGFloat scaleRatio = bounds.size.width / width;
    CGSize imageSize = CGSizeMake(CGImageGetWidth(imgRef), CGImageGetHeight(imgRef));

    UIImageOrientation orient = image.imageOrientation;

    switch(orient) 
    {

        case UIImageOrientationUp: //default
            transform = CGAffineTransformIdentity;
            break;

        default:
            [NSException raise:NSInternalInconsistencyException format:@"Invalid image orientation"];
    }

    UIGraphicsBeginImageContext(bounds.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextScaleCTM(context, scaleRatio, -scaleRatio);
    CGContextTranslateCTM(context, 0, -height);

    CGContextConcatCTM(context, transform);
    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}

请帮忙。

1 个答案:

答案 0 :(得分:1)

您必须使用以下代码

释放CGImageRef和CGContextRef
CGImageRelease(imgRef);
CGContextRelease(context);