分享

UIImage的放缩

 xue_dong5437 2010-10-21

I just tried this, and UIImage does not support _imageScaledToSize.

I ended up adding a method to UIImage using a category - a suggestion I found on the Apple Dev forums.

In a project-wide .h -

@interface UIImage (Extras)
- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize;
@end;

Implementation:

@implementation UIImage (Extras)

- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {

UIImage *sourceImage = self;
UIImage *newImage = nil;

CGSize imageSize = sourceImage.size;
CGFloat width = imageSize.width;
CGFloat height = imageSize.height;

CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;

CGFloat scaleFactor = 0.0;
CGFloat scaledWidth = targetWidth;
CGFloat scaledHeight = targetHeight;

CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

if (CGSizeEqualToSize(imageSize, targetSize) == NO) {

       
CGFloat widthFactor = targetWidth / width;
       
CGFloat heightFactor = targetHeight / height;

       
if (widthFactor < heightFactor)
                scaleFactor
= widthFactor;
       
else
                scaleFactor
= heightFactor;

        scaledWidth  
= width * scaleFactor;
        scaledHeight
= height * scaleFactor;

       
// center the image
if (widthFactor < heightFactor) {
                thumbnailPoint
.y = (targetHeight - scaledHeight) * 0.5;
       
} else if (widthFactor > heightFactor) {
                thumbnailPoint
.x = (targetWidth - scaledWidth) * 0.5;
       
}
}


// this is actually the interesting part:

UIGraphicsBeginImageContext(targetSize);

CGRect thumbnailRect = CGRectZero;
thumbnailRect
.origin = thumbnailPoint;
thumbnailRect
.size.width  = scaledWidth;
thumbnailRect
.size.height = scaledHeight;

[sourceImage drawInRect:thumbnailRect];

newImage
= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

if(newImage == nil) NSLog(@"could not scale image");


return newImage ;
}

@end;

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约