创建一个category
.h
#import <UIKit/UIKit.h>
@interface UIImage (ImageCut)
-(UIImage*)ImageCutSize:(CGRect)rect;
@end
.m
#import "UIImage+ImageCut.h"
@implementation UIImage (ImageCut)
-(UIImage*)ImageCutSize:(CGRect)rect{
CGImageRef subImageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
CGRect smallRect = CGRectMake(0, 0, CGImageGetWidth(subImageRef), CGImageGetHeight(subImageRef));
//开始绘图
UIGraphicsBeginImageContext(smallRect.size);
//获取上下文
CGContextRef context = UIGraphicsGetCurrentContext();
/*参数1:上下文
参数2:剪切图片的大小
参数3:裁剪部分图片内容
*/
CGContextDrawImage(context, smallRect, subImageRef);
UIImage *image= [UIImage imageWithCGImage:subImageRef];
//结束绘图
UIGraphicsEndImageContext();
return image;
}
@end
在ViewController中
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self cutImage];
}
-(void)cutImage{
UIImage *image =[UIImage imageNamed:@"1"];
UIImage *imageNew =[image ImageCutSize:CGRectMake(100, 100, 200, 200)];
UIImageWriteToSavedPhotosAlbum(imageNew, nil, nil, nil);
}
其中最后一句UIImageWriteToSavedPhotosAlbum(imageNew, nil, nil, nil);是将图片保存到手机相册,可以根据程序需要修改保存位置,如果是要保存手机相册,下面的一定要
添加 <key>NSPhotoLibraryUsageDescription</key> <string>App需要您的同意,才能访问相册</string> iOS 10如果访问必须添加否则闪退