iPhone的相機規格性能相當好,以iPhone 6為例,它有800萬畫素,寬高比為3×4或4×3,我們想要讓拍的相片的寬高比變為4×6或6×4,該怎麼做呢?
事情是這樣子,我有相框4×6或6×4,若直接以3×4或4×3影像去適應相框,最後合成的影像鐵定會變形~
/**
Theme: Crop Image to 3:2(2:3)
IDE: Xcode 6
Language: Objective C
Date: 103/10/30
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
*/
#pragma mark - 相片比例取3:2(2:3)
float ratio = 3.0 / 2.0;
float oldWidth = image.size.width;
float oldHeight = image.size.height;
float newWidth;
float newHeight;
UIImage *img;
if (oldWidth > oldHeight) {// 寬比高長(3264,2448)
if (oldWidth / oldHeight < ratio) {// 寬不夠長,截高
newWidth = oldWidth;// 3264
newHeight = oldWidth / ratio;// 2176
CGRect rect = CGRectMake(0, (oldHeight - newHeight) / 2,
newWidth, newHeight);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
else {// 不理會
img = image;
}
}
else {// 高比寬長(2448,3264)
if (oldHeight / oldWidth < ratio) {// 高不夠長,截寬
newHeight = oldHeight;// 3264
newWidth = oldHeight / ratio;// 2176
CGRect rect = CGRectMake(0, (oldWidth - newWidth) / 2,
newHeight, newWidth);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
img = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
}
else {// 不理會
img = image;
}
}
經以上演算法去裁剪影像為4×6或6×4,再去適應4×6或6×4的相框,最終合成影像就不會有拉伸問題囉~
註:不理會的意思是,在本case不會遇到,所以我就沒寫囉~
不過被朋友測出在其它版本裝置還是有拉伸的問題,決定用最基本的方法來一次解決所有螢幕大小,而且不用計算寬高比呢!
我用的方法是疊三層,由底到頂分別為底圖、相片、相框,而這三層都是同相框大小,關鍵在於放置相片Image View的content mode要設定為Scale Aspect Fill,而且影像剛好是置中,如此一來,無論相片要截寬或截高都沒問題了!可參考:UIImageView 的 contentMode 屬性。
/**
Theme: Crop Image to 3:2(2:3)
IDE: Xcode 6
Language: Objective C
Date: 103/11/02
Author: HappyMan
Blog: https://cg2010studio.wordpress.com/
*/
#pragma mark - 疊三層(底圖、相片、相框)輸出圖
UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, frameImage.size.width, frameImage.size.height)];
UIImageView *frameImageView = [[UIImageView alloc] initWithFrame:bottomView.frame];
frameImageView.contentMode = UIViewContentModeScaleAspectFill;
UIImageView *RotatedImageView = [[UIImageView alloc] initWithFrame:bottomView.frame];
RotatedImageView.contentMode = UIViewContentModeScaleAspectFill;
[frameImageView setImage:frameImage];
[RotatedImageView setImage:rotatedImage];
[bottomView addSubview:RotatedImageView];
[bottomView addSubview:frameImageView];





隨意留個言吧:)~