图片剪切 iOS

创建一个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如果访问必须添加否则闪退

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值