最近在研究iOS截图的部分,以下代码可以实现:图片缩放到指定宽度(如果精度不够屏幕精度将不缩放)、截取图片的中间部分
//根据设置短边的大小,将size等比例缩放短边的大小
+ (CGSize)newSize:(CGSize)size minLedge:(CGFloat)minLedge {
CGFloat width = size.width;
CGFloat height = size.height;
CGSize newSize = size;
if (height > width) {//高度为长边
newSize.width = minLedge;
newSize.height = minLedge * height/width;
} else {
newSize.width = minLedge*width/height;
newSize.height = minLedge ;
}
return newSize;
}
//size(屏幕上1x的大小)传的是image同比例的大小 ,image传的是原图,结果得到size*scale大小图
+ (UIImage*)scaleToSize:(CGSize)size forImage:(UIImage *)image {
if (image ==nil) {
returnnil;
}
CGFloat scale = [UIScreenmainScreen].scale;
UIImage* scaledImage = image;
if (image.size.width/size.width > scale) {
// 创建一个bitmap的context
// 并把它设置成为当前正在使用的context
UIGraphicsBeginImageContext(CGSizeMake(size.width * scale, size.height *scale));
// 绘制改变大小的图片
[image drawInRect:CGRectMake(0,0, size.width*scale, size.height*scale)];
// 从当前context中创建一个改变大小后的图片
scaledImage = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
}
// 返回新的改变大小后的图片
return scaledImage;
}
//传入size记得屏幕的1x的size
+ (UIImage *)cutCenterImageSize:(CGSize)size iMg:(UIImage *)img {
CGFloat scale = [UIScreenmainScreen].scale;
size.width = size.width*scale;
size.height = size.height *scale;
CGSize imageSize = img.size;
CGRect rect;
//根据图片的大小计算出图片中间矩形区域的位置与大小
if (imageSize.width > imageSize.height) {
float leftMargin = (imageSize.width - imageSize.height) *0.5;
rect = CGRectMake(leftMargin,0, imageSize.height, imageSize.height);
}else{
float topMargin = (imageSize.height - imageSize.width) *0.5;
rect = CGRectMake(0, topMargin, imageSize.width, imageSize.width);
}
CGImageRef imageRef = img.CGImage;
//截取中间区域矩形图片
CGImageRef imageRefRect =CGImageCreateWithImageInRect(imageRef, rect);
UIImage *tmp = [[UIImagealloc] initWithCGImage:imageRefRect];
CGImageRelease(imageRefRect);
UIGraphicsBeginImageContext(size);
CGRect rectDraw =CGRectMake(0,0, size.width, size.height);
[tmp drawInRect:rectDraw];
// 从当前context中创建一个改变大小后的图片
tmp = UIGraphicsGetImageFromCurrentImageContext();
// 使当前的context出堆栈
UIGraphicsEndImageContext();
NSLog(@"tmp sizewidth is %f sizeHeight is %f",tmp.size.width,tmp.size.height);
return tmp;
}