博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
IOS实用功能之截图(来自相册和拍照)
阅读量:5317 次
发布时间:2019-06-14

本文共 10117 字,大约阅读时间需要 33 分钟。

//

//  ViewController.m

//  MyImagePicker1.0

//

//  Created by Mac on 14-7-14.

//  Copyright (c) 2014年 Digital media technology. All rights reserved.

//

#import "ViewController.h"

#import "VPImageCropperViewController.h"

#import <AssetsLibrary/AssetsLibrary.h>

#import <MobileCoreServices/MobileCoreServices.h>

#define ORIGINAL_MAX_WIDTH 640.0f

@interfaceViewController () <UINavigationControllerDelegate,UIImagePickerControllerDelegate, UIActionSheetDelegate,VPImageCropperDelegate>

@property (weak, nonatomic)IBOutletUIImageView *imageView;

@end

@implementation ViewController

- (void)viewDidLoad

{

    [superviewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

    

    //do some init job for UIImageView

    

    [self.imageView.layersetCornerRadius:(self.imageView.frame.size.height/2)];

    [self.imageView.layersetMasksToBounds:YES];

    [self.imageViewsetContentMode:UIViewContentModeScaleAspectFill];

    [self.imageViewsetClipsToBounds:YES];

    

    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(tapGRAction)];

    

    self.imageView.layer.borderWidth = 1.0;

    self.imageView.layer.borderColor = [[UIColorblackColor] CGColor];

    [self.imageViewaddGestureRecognizer:tapGR];

    

    //load an image

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {

        NSURL *portraitUrl = [NSURLURLWithString:@"http://photo.l99.com/bigger/31/1363231021567_5zu910.jpg"];

        UIImage *protraitImg = [UIImageimageWithData:[NSDatadataWithContentsOfURL:portraitUrl]];

        dispatch_sync(dispatch_get_main_queue(), ^{

            self.imageView.image = protraitImg;

        });

    });

}

-(void)tapGRAction{

    

    NSLog(@"tap");

    

    UIActionSheet *actionSheet = [[UIActionSheetalloc] initWithTitle:@"选择"delegate:selfcancelButtonTitle:@"Cancel"destructiveButtonTitle:nilotherButtonTitles:@"Take photo",@"From Albums", nil];

    

    [actionSheet showInView:self.view];

    

}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{

    

    switch (buttonIndex) {

        case 0:

            NSLog(@"Take photo");

            // 拍照

            if ([selfisCameraAvailable] && [selfdoesCameraSupportTakingPhotos]) {

                UIImagePickerController *controller = [[UIImagePickerControlleralloc] init];

                controller.sourceType =UIImagePickerControllerSourceTypeCamera;

                if ([selfisFrontCameraAvailable]) {

                    controller.cameraDevice =UIImagePickerControllerCameraDeviceFront;

                }

                NSMutableArray *mediaTypes = [[NSMutableArrayalloc] init];

                [mediaTypes addObject:(__bridgeNSString *)kUTTypeImage];

                controller.mediaTypes = mediaTypes;

                controller.delegate = self;

                [self presentViewController:controller

                                   animated:YES

                                 completion:^(void){

                                     NSLog(@"Picker View Controller is presented");

                                 }];

            }

            

            break;

        case 1:

            NSLog(@"Albums");

            // 从相册中选取

            if ([selfisPhotoLibraryAvailable]) {

                UIImagePickerController *controller = [[UIImagePickerControlleralloc] init];

                controller.sourceType =UIImagePickerControllerSourceTypePhotoLibrary;

                NSMutableArray *mediaTypes = [[NSMutableArrayalloc] init];

                [mediaTypes addObject:(__bridgeNSString *)kUTTypeImage];

                controller.mediaTypes = mediaTypes;

                controller.delegate = self;

                [self presentViewController:controller

                                   animated:YES

                                 completion:^(void){

                                     NSLog(@"Picker View Controller is presented");

                                 }];

            }

            break;

            

        default:

            break;

    }

    

}

#pragma mark VPImageCropperDelegate

- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)editedImage {

    self.imageView.image = editedImage;

    

//    [self.imageView.layer setCornerRadius:(self.imageView.frame.size.height/2)];

//    [self.imageView.layer setMasksToBounds:YES];

//    [self.imageView setContentMode:UIViewContentModeScaleAspectFill];

//    [self.imageView setClipsToBounds:YES];

    

    [cropperViewController dismissViewControllerAnimated:YEScompletion:^{

        // TO DO

    }];

}

- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {

    [cropperViewController dismissViewControllerAnimated:YEScompletion:^{

    }];

}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    [picker dismissViewControllerAnimated:YEScompletion:^() {

        UIImage *portraitImg = [infoobjectForKey:@"UIImagePickerControllerOriginalImage"];

        portraitImg = [self imageByScalingToMaxSize:portraitImg];

        // 裁剪

        VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewControlleralloc] initWithImage:portraitImg cropFrame:CGRectMake(0, 100.0f, self.view.frame.size.width,self.view.frame.size.width)limitScaleRatio:3.0];

        imgEditorVC.delegate = self;

        [selfpresentViewController:imgEditorVC animated:YEScompletion:^{

            // TO DO

        }];

    }];

}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {

    [picker dismissViewControllerAnimated:YEScompletion:^(){

    }];

}

#pragma mark - UINavigationControllerDelegate

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {

    

}

#pragma mark camera utility

- (BOOL) isCameraAvailable{

    return [UIImagePickerControllerisSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];

}

- (BOOL) isRearCameraAvailable{

    return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];

}

- (BOOL) isFrontCameraAvailable {

    return [UIImagePickerControllerisCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];

}

- (BOOL) doesCameraSupportTakingPhotos {

    return [selfcameraSupportsMedia:(__bridgeNSString *)kUTTypeImagesourceType:UIImagePickerControllerSourceTypeCamera];

}

- (BOOL) isPhotoLibraryAvailable{

    return [UIImagePickerControllerisSourceTypeAvailable:

            UIImagePickerControllerSourceTypePhotoLibrary];

}

- (BOOL) canUserPickVideosFromPhotoLibrary{

    return [self

            cameraSupportsMedia:(__bridgeNSString *)kUTTypeMoviesourceType:UIImagePickerControllerSourceTypePhotoLibrary];

}

- (BOOL) canUserPickPhotosFromPhotoLibrary{

    return [self

            cameraSupportsMedia:(__bridgeNSString *)kUTTypeImagesourceType:UIImagePickerControllerSourceTypePhotoLibrary];

}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{

    __block BOOL result =NO;

    if ([paramMediaType length] == 0) {

        return NO;

    }

    NSArray *availableMediaTypes = [UIImagePickerControlleravailableMediaTypesForSourceType:paramSourceType];

    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj,NSUInteger idx, BOOL *stop) {

        NSString *mediaType = (NSString *)obj;

        if ([mediaType isEqualToString:paramMediaType]){

            result = YES;

            *stop= YES;

        }

    }];

    return result;

}

#pragma mark image scale utility

- (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage {

    if (sourceImage.size.width <ORIGINAL_MAX_WIDTH) return sourceImage;

    CGFloat btWidth = 0.0f;

    CGFloat btHeight = 0.0f;

    if (sourceImage.size.width > sourceImage.size.height) {

        btHeight = ORIGINAL_MAX_WIDTH;

        btWidth = sourceImage.size.width * (ORIGINAL_MAX_WIDTH / sourceImage.size.height);

    } else {

        btWidth = ORIGINAL_MAX_WIDTH;

        btHeight = sourceImage.size.height * (ORIGINAL_MAX_WIDTH / sourceImage.size.width);

    }

    CGSize targetSize = CGSizeMake(btWidth, btHeight);

    return [selfimageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];

}

- (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {

    UIImage *newImage = nil;

    CGSize imageSize = sourceImage.size;

    CGFloat width = imageSize.width;

    CGFloat height = imageSize.height;

    CGFloat targetWidth = targetSize.width;

    CGFloat targetHeight = targetSize.height;

    CGFloat scaleFactor = 0.0;

    CGFloat scaledWidth = targetWidth;

    CGFloat scaledHeight = targetHeight;

    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);

    if (CGSizeEqualToSize(imageSize, targetSize) ==NO)

    {

        CGFloat widthFactor = targetWidth / width;

        CGFloat heightFactor = targetHeight / height;

        

        if (widthFactor > heightFactor)

            scaleFactor = widthFactor; // scale to fit height

        else

            scaleFactor = heightFactor; // scale to fit width

        scaledWidth  = width * scaleFactor;

        scaledHeight = height * scaleFactor;

        

        // center the image

        if (widthFactor > heightFactor)

        {

            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;

        }

        else

            if (widthFactor < heightFactor)

            {

                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;

            }

    }

    UIGraphicsBeginImageContext(targetSize);// this will crop

    CGRect thumbnailRect = CGRectZero;

    thumbnailRect.origin = thumbnailPoint;

    thumbnailRect.size.width  = scaledWidth;

    thumbnailRect.size.height = scaledHeight;

    

    [sourceImage drawInRect:thumbnailRect];

    

    newImage = UIGraphicsGetImageFromCurrentImageContext();

    if(newImage ==nil) NSLog(@"could not scale image");

    

    //pop the context to get back to the default

    UIGraphicsEndImageContext();

    return newImage;

}

#pragma mark portraitImageView getter

- (UIImageView *)portraitImageView {

    if (!self.imageView) {

        CGFloat w = 100.0f; CGFloat h = w;

        CGFloat x = (self.view.frame.size.width - w) / 2;

        CGFloat y = (self.view.frame.size.height - h) / 2;

        self.imageView = [[UIImageViewalloc] initWithFrame:CGRectMake(x, y, w, h)];

        

        //把图像变成圆形的代码

        [self.imageView.layersetCornerRadius:(self.imageView.frame.size.height/2)];

        [self.imageView.layersetMasksToBounds:YES];

        [self.imageViewsetContentMode:UIViewContentModeScaleAspectFill];

        [self.imageViewsetClipsToBounds:YES];

        

        //设置阴影

        self.imageView.layer.shadowColor = [UIColorblackColor].CGColor;

        self.imageView.layer.shadowOffset =CGSizeMake(4, 4);

        self.imageView.layer.shadowOpacity = 0.5;

        self.imageView.layer.shadowRadius = 2.0;

        

        //设置边框的大小和颜色

        self.imageView.layer.borderColor = [[UIColorblackColor] CGColor];

        self.imageView.layer.borderWidth = 2.0f;

        

        self.imageView.userInteractionEnabled =YES;

        self.imageView.backgroundColor = [UIColorblackColor];

        UITapGestureRecognizer *portraitTap = [[UITapGestureRecognizeralloc] initWithTarget:selfaction:@selector(editPortrait)];

        [self.imageViewaddGestureRecognizer:portraitTap];

    }

    returnself.imageView;

}

- (void)didReceiveMemoryWarning

{

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

 

转载于:https://www.cnblogs.com/IOS-Developer/p/4117235.html

你可能感兴趣的文章
点击User Profile Service Application 报错
查看>>
VS2010插件之NuGet
查看>>
1.单机部署hadoop测试环境
查看>>
[设计模式]桥接模式
查看>>
734. [网络流24题] 方格取数问题 二分图点权最大独立集/最小割/最大流
查看>>
关于input type=file 限制文件上传类型
查看>>
深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap[转]
查看>>
[转载]工作面试时最难的25个问题
查看>>
Test
查看>>
HMAC
查看>>
linux进阶命令2
查看>>
实训三(cocos2dx 3.x 打包apk)
查看>>
【基础操作】线性基详解
查看>>
Git删除分支/恢复分支
查看>>
IIS7中使用集成模式时出现HttpException
查看>>
NOI导刊模拟2—电话网络 解题报告
查看>>
【代码笔记】iOS-播放从网络上下载的语音
查看>>
c# 操作excle
查看>>
JDK中DNS缓存的分析
查看>>
Objective-C中的@property和@synthesize用法
查看>>