// // CropImageController.m // CropImage // // Created by limuyun on 2017/1/10. // Copyright © 2017年 biiway. All rights reserved. // #import "CropImageController.h" //#import "UIImage+Crop.h" #import "GlobalUtlis.h" #import "UIImageCrop.h" #define ScreenWidth [UIScreen mainScreen].bounds.size.width #define ScreenHeight [UIScreen mainScreen].bounds.size.height @interface CropImageController () @property (nonatomic, strong) UIScrollView * scrollView; @property (nonatomic, strong) UIImageView * imageView; @property (nonatomic, strong) UIImage * originalImage; @property (nonatomic, strong) NSString* mCropPicturePath; //extern int Widget_LanguageID; @end @implementation CropImageController{ NSString * textCancel; NSString * textSelect; } - (instancetype)initWithImage:(UIImage *)originalImage delegate:(id)delegate { self = [super init]; if (self) { _delegate = delegate; _originalImage = originalImage; } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor blackColor]; self.automaticallyAdjustsScrollViewInsets = NO; [self initLlanguage]; if(_mRATIO_X <= 0){ _mRATIO_X = 1; } if(_mRATIO_Y <= 0){ _mRATIO_Y = 1; } CGFloat heightN = ScreenWidth*_mRATIO_Y/_mRATIO_X; CGFloat height = (ScreenHeight - heightN)/2.0; _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, height ,ScreenWidth, heightN)]; _scrollView.bouncesZoom = YES; _scrollView.minimumZoomScale = 1; _scrollView.maximumZoomScale = 3; _scrollView.zoomScale = 1; _scrollView.delegate = self; _scrollView.layer.masksToBounds = NO; _scrollView.showsHorizontalScrollIndicator = NO; _scrollView.showsVerticalScrollIndicator = NO; _scrollView.layer.borderWidth = 1.5; _scrollView.layer.borderColor = [UIColor whiteColor].CGColor; if (_ovalClip) { _scrollView.layer.cornerRadius = ScreenWidth/2.0; } self.view.layer.masksToBounds = YES; if (_originalImage) { _imageView = [[UIImageView alloc] initWithImage:_originalImage]; CGFloat img_width = ScreenWidth; CGFloat img_height = _originalImage.size.height * (img_width/_originalImage.size.width); CGFloat img_y= (img_height - self.view.bounds.size.width)/2.0; _imageView.frame = CGRectMake(0,0, img_width, img_height); _imageView.userInteractionEnabled = YES; [_scrollView addSubview:_imageView]; _scrollView.contentSize = CGSizeMake(img_width, img_height); _scrollView.contentOffset = CGPointMake(0, img_y); [self.view addSubview:_scrollView]; } if(_mCropFileName == nil || _mCropFileName.length == 0 ){ _mCropFileName = @"hdl_headPicture"; } [self userInterface]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self.navigationController setNavigationBarHidden:YES]; } - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; [self.navigationController setNavigationBarHidden:NO]; } - (void)userInterface { CGRect cropframe = _scrollView.frame; UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:self.view.bounds cornerRadius:0]; UIBezierPath * cropPath = [UIBezierPath bezierPathWithRoundedRect:cropframe cornerRadius:0]; if (_ovalClip) { cropPath = [UIBezierPath bezierPathWithOvalInRect:cropframe]; } [path appendPath:cropPath]; CAShapeLayer * layer = [[CAShapeLayer alloc] init]; layer.fillColor = [UIColor colorWithRed:.0 green:.0 blue:.0 alpha:0.5].CGColor; layer.fillRule=kCAFillRuleEvenOdd; layer.path = path.CGPath; [self.view.layer addSublayer:layer]; UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - 46, self.view.bounds.size.width, 46)]; view.backgroundColor = [UIColor colorWithRed:30/255.0 green:30/255.0 blue:30/255.0 alpha:0.7]; [self.view addSubview:view]; UIButton * canncelBtn = [UIButton buttonWithType:UIButtonTypeSystem]; // [canncelBtn setBackgroundImage:[UIImage imageNamed:@"ic_widget_cancel"] forState:UIControlStateNormal]; canncelBtn.frame = CGRectMake(0, 0, 60, 44); canncelBtn.titleLabel.font = [UIFont systemFontOfSize:16]; // [canncelBtn setTitle: NSLocalizedString(@"action_cancel", @"") forState:UIControlStateNormal]; [canncelBtn setTitle:textCancel forState:UIControlStateNormal]; [canncelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [canncelBtn addTarget:self action:@selector(cancelBtnClick) forControlEvents:UIControlEventTouchUpInside]; [view addSubview:canncelBtn]; UIButton * doneBtn = [UIButton buttonWithType:UIButtonTypeSystem]; doneBtn.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 60, 0, 60, 44); // [doneBtn setBackgroundImage:[UIImage imageNamed:@"ic_widget_cancel"] forState:UIControlStateNormal]; doneBtn.titleLabel.font = [UIFont systemFontOfSize:16]; [doneBtn setTitle:textSelect forState:UIControlStateNormal]; [doneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [doneBtn addTarget:self action:@selector(doneBtnClick) forControlEvents:UIControlEventTouchUpInside]; [view addSubview:doneBtn]; // if(Widget_LanguageID == 1){ // [canncelBtn setTitle: @"Cancel" forState:UIControlStateNormal]; // [doneBtn setTitle: @"Save" forState:UIControlStateNormal]; // }else{ // [canncelBtn setTitle: @"取消" forState:UIControlStateNormal]; // [doneBtn setTitle: @"保存" forState:UIControlStateNormal]; // } } -(void)initLlanguage{ NSString *languageName = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0]; // 简体中文 if ([languageName rangeOfString:@"zh-Hans"].location != NSNotFound) { textCancel = @"取消"; textSelect = @"选取"; }else{ textCancel = @"Cancel"; textSelect = @"Select"; } } #pragma mark -- UIScrollViewDelegate - (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView { return self.imageView; } - (void)scrollViewDidZoom:(UIScrollView *)scrollView { //调整位置 [self centerContent]; } - (void)centerContent { CGRect imageViewFrame = _imageView.frame; CGRect scrollBounds = CGRectMake(0, 0, ScreenWidth, ScreenWidth); if (imageViewFrame.size.height > scrollBounds.size.height) { imageViewFrame.origin.y = 0.0f; }else { imageViewFrame.origin.y = (scrollBounds.size.height - imageViewFrame.size.height) / 2.0; } if (imageViewFrame.size.width < scrollBounds.size.width) { imageViewFrame.origin.x = (scrollBounds.size.width - imageViewFrame.size.width) /2.0; }else { imageViewFrame.origin.x = 0.0f; } _imageView.frame = imageViewFrame; } - (void)cancelBtnClick{ if (_delegate && [_delegate respondsToSelector:@selector(cropImageDidFinishedWithImage:bSuccess:)]) { [_delegate cropImageDidFinishedWithImage:nil bSuccess:NO]; } // [self.navigationController popViewControllerAnimated:YES]; [self dismissViewControllerAnimated:YES completion:nil]; } - (UIImage *)cropImage { CGPoint offset = _scrollView.contentOffset; //图片缩放比例 CGFloat zoom = _imageView.frame.size.width/_originalImage.size.width; //视网膜屏幕倍数相关 zoom = zoom / [UIScreen mainScreen].scale; CGFloat width = _scrollView.frame.size.width; CGFloat height = _scrollView.frame.size.height; if (_imageView.frame.size.height < _scrollView.frame.size.height) {//太胖了,取中间部分 offset = CGPointMake(offset.x + (width - _imageView.frame.size.height)/2.0, 0); width = height = _imageView.frame.size.height; } CGRect rec = CGRectMake(offset.x/zoom, offset.y/zoom,width/zoom,height/zoom); CGImageRef imageRef =CGImageCreateWithImageInRect([_originalImage CGImage],rec); UIImage * image = [[UIImage alloc]initWithCGImage:imageRef]; CGImageRelease(imageRef); if (_ovalClip) { image = [UIImageCrop ovalClip:image]; // image = zipNSDataWithImage } image = [self compressImageSize:image toByte:200*1024]; return image; } -(NSString*)saveImage{ NSString* _mCropPicturePath = @""; NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString *filePath = [[paths objectAtIndex:0]stringByAppendingPathComponent: [NSString stringWithFormat:@"%@%@", _mCropFileName,@".Png"]]; // 保存文件的名称 BOOL result = [UIImagePNGRepresentation([self cropImage])writeToFile:filePath atomically:YES]; // 保存成功会返回YES if (result == YES) { _mCropPicturePath = filePath; NSLog(@"保存成功"); }else{ _mCropPicturePath = @""; } return _mCropPicturePath; } - (void)doneBtnClick{ NSString* saveSuccessath = [self saveImage]; BOOL saveSuccess = NO; if(![saveSuccessath isEqualToString:@""]){ saveSuccess = YES; } if (_delegate && [_delegate respondsToSelector:@selector(cropImageDidFinishedWithImage:bSuccess:)]) { [_delegate cropImageDidFinishedWithImage:saveSuccessath bSuccess:saveSuccess]; } // [self.navigationController popViewControllerAnimated:YES]; [self dismissViewControllerAnimated:YES completion:nil]; } #pragma mark - UIStatusBarStyle - (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleLightContent; } - (BOOL)prefersStatusBarHidden { return NO; } //-(NSData *)zipNSDataWithImage:(UIImage *)sourceImage{ // //进行图像的画面质量压缩 // NSData *data=UIImageJPEGRepresentation(sourceImage, 1.0); // if (data.length>100*1024) { // if (data.length>1024*1024) {//1M以及以上 // data=UIImageJPEGRepresentation(sourceImage, 0.5); // if (data.length>1024*1024) {//1M以及以上 // data=UIImageJPEGRepresentation(sourceImage, 0.5); // } // }else if (data.length>512*1024) {//0.5M-1M // data=UIImageJPEGRepresentation(sourceImage, 0.6); // }else if (data.length>200*1024) { // //0.25M-0.5M // data=UIImageJPEGRepresentation(sourceImage, 0.7); // } // } // return data; //} //图片压缩 - (UIImage *)compressImageSize:(UIImage *)image toByte:(NSUInteger)maxLength { UIImage *resultImage = image; NSData *data = UIImageJPEGRepresentation(resultImage, 1); NSUInteger lastDataLength = 0; while (data.length > maxLength && data.length != lastDataLength) { lastDataLength = data.length; CGFloat ratio = (CGFloat)maxLength / data.length; CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank UIGraphicsBeginImageContext(size); // Use image to draw (drawInRect:), image is larger but more compression time // Use result image to draw, image is smaller but less compression time [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)]; resultImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); data = UIImageJPEGRepresentation(resultImage, 1); } return resultImage; } @end