將一幅圖片按著需要的尺寸進行等比的壓縮和放大,最後再截取需要尺寸部分,不知道說清楚沒,反正就那意思吧!
+(UIImage *)compressImageWith:(UIImage *)image width:(float)width height:(float)height { float imageWidth = image.size.width; float imageHeight = image.size.height; float widthScale = imageWidth /width; float heightScale = imageHeight /height; // 創建一個bitmap的context // 並把它設置成為當前正在使用的context UIGraphicsBeginImageContext(CGSizeMake(width, height)); if (widthScale > heightScale) { [image drawInRect:CGRectMake(0, 0, imageWidth /heightScale , height)]; } else { [image drawInRect:CGRectMake(0, 0, width , imageHeight /widthScale)]; } // 從當前context中創建一個改變大小後的圖片 UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext(); [newImage retain]; // 使當前的context出堆棧 UIGraphicsEndImageContext(); return newImage; }