アットウィキロゴ

解像度を維持してリサイズ

#pragma mark - 解像度を維持してリサイズ
+ (UIImage *)shrinkImage:(UIImage *)image 
              shrinkSize:(CGSize)shrinkSize {
 
 
    UIImage *newImage = nil;
 
    CGSize imageSize = image.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
 
    CGFloat targetWidth = shrinkSize.width;
    CGFloat targetHeight = shrinkSize.height;
 
    CGFloat scaleFactor = 0.0f;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
 
    CGPoint thumbnailPoint = CGPointMake(0.0f, 0.0f);
 
    if (CGSizeEqualToSize(imageSize, shrinkSize) == 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.5f; 
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5f;
        }
    }
 
    // this is actually the interesting part:
    UIGraphicsBeginImageContext(shrinkSize);
 
    [[UIColor blackColor] set];
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextFillRect(context, CGRectMake(0.0f, 0.0f, targetWidth, targetHeight));
 
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
 
    [image drawInRect:thumbnailRect];
 
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
 
    if (newImage == nil) NSLog(@"画像を拡大·縮小することができませんでした");
 
    return newImage ;
}

タグ:

+ タグ編集
  • タグ:
最終更新:2012年09月11日 09:20
ツールボックス

下から選んでください:

新しいページを作成する
ヘルプ / FAQ もご覧ください。