引言
一般在制作天空盒子的時候笼才,UI給的圖片資源都是如下圖那般溢谤,對于我們來制作天空盒子的時候是還不夠的壶辜,所以本著能自己解決的事悯舟,絕不找人的原則,我們需要對圖片進行裁剪砸民。
image.png
實現(xiàn)效果
將上圖裁剪成下圖的樣子
image.png
思路
首先我們將圖片分為六個面:前抵怎、后、左岭参、右反惕、上、下(如下圖)演侯,從圖片中可以看出姿染,每一個面都是正方形的,即找到每一張圖的左上角頂點就可以求出單個圖片的大小和位置秒际。圖片的總寬度/4 即求出單個圖片的length尺寸悬赏,這樣子就可以很簡單地獲取到每一個圖片的位置和尺寸。例如:front的左上角頂點位置為(length, length)娄徊,right的左上角頂點位置是(2 * length, length);
image.png
源碼實例
#import "ViewController.h"
@interface ViewController ()
@property(nonatomic,strong)UIImageView *imageView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1.創(chuàng)建一個寬100闽颇,長100*6的圖片view(天空盒子圖片大小:100 * 100 ,6張)
self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 88, 100, 100 * 6)];
self.imageView.center = self.view.center;
//2.設置圖片
UIImage *cImage = [UIImage imageNamed:@"skybox2.png"];
//3.加載圖片
[self.imageView setImage:cImage];
//4
[self.view addSubview:self.imageView];
//處理圖片
//1.獲取圖片的長度
long length = cImage.size.width/4;
//2.圖片頂點索引
long indices[] = {
length * 2, length, // 右
0, length, // 左
length, 0, // 上 top
length, length * 2, // 底bottom
length, length ,// 頂front
length * 3, length, // 背面
};
//3.指定圖片個數(shù)
//為什么除以2?因為包含了x寄锐,y
long faceCount = sizeof(indices)/sizeof(indices[0])/2;
//4.獲取圖片大小 單個圖片大斜唷:length * length, 組合起來:length,length * faceCount
CGSize imageSize = {length, length * faceCount};
//5. 創(chuàng)建基于位圖的圖形上下文并使其成為當前上下文橄仆。
UIGraphicsBeginImageContext(imageSize);
for (int i = 0; i + 2 <= faceCount * 2; i += 2) {
//創(chuàng)建圖片剩膘,從CImage。CGImage盆顾,獲取位置rect上的圖片
CGImageRef cgImage = CGImageCreateWithImageInRect(cImage.CGImage, CGRectMake(indices[i], indices[i + 1], length, length));
//將CGImage轉(zhuǎn)換為UIImage
UIImage *tmp = [UIImage imageWithCGImage:cgImage];
//繪制圖片
[tmp drawInRect:CGRectMake(0, length * i / 2, length, length)];
}
//6.獲取處理好的圖片
//UIGraphicsGetImageFromCurrentImageContext 基于當前位圖基于圖形上下文的內(nèi)容返回圖像怠褐。只有在基于位圖的圖形上下文是當前圖形上下文時,才應該調(diào)用此函數(shù)您宪。如果目前的情況下是零或沒有通過UIGraphicsBeginImageContext創(chuàng)建奈懒,這個函數(shù)返回nil具温。
UIImage *finalImg = UIGraphicsGetImageFromCurrentImageContext();
[self.imageView setImage:finalImg];
//打印圖片信息
NSLog(@"final:%@", [finalImg description]);
//7.保存圖片到沙河
//指定圖片路徑
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"box.png"];
//打印路徑
NSLog(@"image path:%@", path);
//獲取圖片數(shù)據(jù)-png格式的圖片數(shù)據(jù)
//UIImagePNGRepresentation(imgData)以PNG格式返回指定圖像的數(shù)據(jù)
NSData *cImageData = UIImagePNGRepresentation(finalImg);
//寫入文件
BOOL writeStatus = [cImageData writeToFile:path atomically:YES];
if (writeStatus) {
NSLog(@"處理天空盒子圖片成功~~");
}else {
NSLog(@"處理圖片失敗筐赔!");
}
}
GitHub代碼: YSMakeSkyBoxImage.git