您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 使用技巧 >> iOS 7 技巧

iOS UIImage 依螢幕寬度等比縮放的實作教學

編輯:iOS 7 技巧

需求很常見:圖片要鋪滿螢幕寬度,高度則依原始比例自動換算,不能變形也不能裁掉。做法是把縮放邏輯寫成 UIImage 的分類(Category),之後任何地方都能直接呼叫。

建立分類

#import "UIImage+UIImageExtras.h"

@implementation UIImage (UIImageExtras)

- (UIImage *)imageByScalingToSize:(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;

        // 取較小的比例,確保內容完整不被裁切
        scaleFactor = (widthFactor < heightFactor) ? widthFactor : heightFactor;
        scaledWidth  = width  * scaleFactor;
        scaledHeight = height * scaleFactor;

        // 依剩餘空間做置中
        if (widthFactor < heightFactor) {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        } else if (widthFactor > heightFactor) {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }

    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

使用方式

CGSize size = image.size;
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;

image = [image imageByScalingToSize:
    CGSizeMake(screenWidth, screenWidth * (size.height / size.width))];

self.imageView.image = image;

兩點提醒

一是這個寫法會重新繪製一張位圖,等於在記憶體中產生新物件。清單大量套用時,建議在資料來源階段算好尺寸並快取,而不是在 scrollView 每次回調時重算。

二是若你只需要顯示層的縮放、不在意實際像素,直接用 contentMode = UIViewContentModeScaleAspectFit 搭配正確的 frame 會省下大量運算。重新繪製只在需要真的改變圖片資料(例如要上傳或存成縮圖)時才有必要。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved