iOS图片合成————(拍照换发)

一个简单的换发小程序,可以实现拍照,移动发型,放大缩小发型。

如图:

iOS图片合成————(拍照换发)_第1张图片


.h中实现:

#import 

@interface ChangeHairVC : UIViewController
@property (strong, nonatomic) IBOutlet UIView *photoView;
@property (weak, nonatomic) IBOutlet UIImageView *personImage;
@property (weak, nonatomic) IBOutlet UIImageView *hairImage;

//合并图片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2;

@end

.m中实现:

#define IsIOS7 ([[[[UIDevice currentDevice] systemVersion] substringToIndex:1] intValue]>=7)
#define IsIPHONE4 ([[UIScreen mainScreen] bounds].size.height < 500)

#import "ChangeHairVC.h"

@interface ChangeHairVC ()

@end



@implementation ChangeHairVC {
    
    CGSize imageSize;//图片的宽高
    CGPoint imagePoint;//图片的位置
    CGPoint startLocation;//移动起始位置
    CGPoint endLocation;//移动终止位置
    CGFloat lastScale;

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithRed:234/255.0 green:244/255.0 blue:235/255.0 alpha:1];
    
    self.photoView.frame = CGRectMake(0, (IsIOS7?20:0)-90, 320, 90);
    [self.view addSubview:self.photoView];
   
    self.personImage.clipsToBounds = YES;
    self.hairImage.clipsToBounds = YES;
    [self.hairImage setImage:[UIImage imageNamed:@"jiafa.png"]];
    
    //限定显示比例
    double n = 320/self.personImage.image.size.width;
    double m = 280/self.hairImage.image.size.width;
    
    
    self.personImage.frame = CGRectMake(0, 44+(IsIOS7?20:0), 320, self.personImage.image.size.height*n);
    self.hairImage.frame = CGRectMake(20, 64+(IsIOS7?20:0), 280, self.hairImage.image.size.height*m);
   
    imageSize.width = self.hairImage.frame.size.width;
    imageSize.height = self.hairImage.frame.size.height;
    imagePoint.x = self.hairImage.frame.origin.x;
    imagePoint.y = self.hairImage.frame.origin.y;
    
    //移动发型图片
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePanGestures:)];
    panGestureRecognizer.minimumNumberOfTouches = 1;
    panGestureRecognizer.maximumNumberOfTouches = 1;
    [self.hairImage addGestureRecognizer:panGestureRecognizer];
    
    //放大缩小发型图片
    UIPinchGestureRecognizer *zoomRecognizer = [[UIPinchGestureRecognizer alloc]initWithTarget:self action:@selector(zoomGesture:)];
    [zoomRecognizer setDelegate:self];
    [self.hairImage addGestureRecognizer:zoomRecognizer];
    
    
}
//合成图片按钮
- (IBAction)mixImage:(id)sender {
    [self addImage:self.personImage.image toImage:self.hairImage.image];
}


//合并图片
- (UIImage *)addImage:(UIImage *)image1 toImage:(UIImage *)image2{
    //设置合成后图片的大小
    UIGraphicsBeginImageContext(self.personImage.frame.size);
    
    [image1 drawInRect:CGRectMake(self.personImage.frame.origin.x, 0, self.personImage.frame.size.width, self.personImage.frame.size.height)];
    
    [image2 drawInRect:CGRectMake(self.hairImage.frame.origin.x, 19, self.hairImage.frame.size.width, self.hairImage.frame.size.height)];
    
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    self.hairImage.hidden = YES;
    //resultingImage即为合成之后的图片
    self.personImage.image = resultingImage;
    return resultingImage;
    
}

//放大缩小
-(void)zoomGesture:(UIPinchGestureRecognizer *)sender {
    
    //当手指离开屏幕时,将lastscale设置为1.0
    if(sender.state == UIGestureRecognizerStateEnded) {
        lastScale = 1.0;
        return;
    }
    if (self.hairImage.frame.origin.x > 0 || self.hairImage.frame.origin.x < [UIScreen mainScreen].bounds.size.width) {
        CGFloat scale = 1.0 - (lastScale - sender.scale);
        CGAffineTransform currentTransform = sender.view.transform;
        CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
        [sender.view setTransform:newTransform];
        lastScale = sender.scale;
        imageSize.width = self.hairImage.frame.size.width;
        imageSize.height = self.hairImage.frame.size.height;
        imagePoint.x = self.hairImage.frame.origin.x;
        imagePoint.y = self.hairImage.frame.origin.y;
       
    }
    
}
#pragma mark - UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return ![gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
//移动图片
- (void) handlePanGestures:(UIPanGestureRecognizer*)paramSender{
    //图片宽高比
    double m = self.hairImage.frame.size.width/self.hairImage.image.size.width;
    if (paramSender.state == UIGestureRecognizerStateBegan){
        //通过使用 locationInView 这个方法,来获取到手势的坐标
        CGPoint location = [paramSender locationInView:paramSender.view.superview];
       //记录图片初始位置
        startLocation.x = location.x;
        startLocation.y = location.y;
        
    }
    if (paramSender.state == UIGestureRecognizerStateChanged) {
        CGPoint location = [paramSender locationInView:paramSender.view.superview];
        //记录图片终止位置
        endLocation.x = location.x;
        endLocation.y = location.y;
        double changeX = endLocation.x - startLocation.x;
        double changeY = endLocation.y - startLocation.y;
        //更改图片位置
        self.hairImage.frame = CGRectMake(imagePoint.x + changeX,  imagePoint.y + changeY,  self.hairImage.frame.size.width, self.hairImage.image.size.height*m);
    }
    
}
//获取照片
#pragma mark photo
- (IBAction)takePhotoClick:(UIButton *)sender {
    [UIView animateWithDuration:0.3 animations:^{
        self.photoView.frame = CGRectMake(0, (IsIOS7?20:0), 320, 90);
    }completion:^(BOOL finished) {
    }];
}


- (IBAction)photoBtnClick:(UIButton *)sender {
    if (sender.tag == 1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.photoView.frame = CGRectMake(0, (IsIOS7?20:0)-90, 320, 90);
            self.hairImage.hidden = NO;
        }completion:^(BOOL finished) {
        }];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
            picker.delegate = self;
            picker.allowsEditing = YES;//设置可编辑
            picker.sourceType = sourceType;
            //创建叠加层
            UIView *overLayView=[[UIView alloc]initWithFrame:CGRectMake(0, 120, 320, 254)];
            //取景器的背景图片,该图片中间挖掉了一块变成透明,用来显示摄像头获取的图片;
            UIImage *overLayImag=[UIImage imageNamed:@"zhaoxiangdingwei.png"];
            UIImageView *bgImageView=[[UIImageView alloc]initWithImage:overLayImag];
            [overLayView addSubview:bgImageView];
            picker.cameraOverlayView=overLayView;
            picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;
            [self presentViewController:picker animated:YES completion:^{
            }];
        }
        else {
            NSLog(@"无相机");
        }
    }
    else if (sender.tag == 2) {
        [UIView animateWithDuration:0.3 animations:^{
            self.photoView.frame = CGRectMake(0, (IsIOS7?20:0)-90, 320, 90);
             self.hairImage.hidden = NO;
        }completion:^(BOOL finished) {
        }];
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = NO;
        [self presentViewController:pickerImage animated:YES completion:^{
            
        }];
    }
    else if (sender.tag == 3) {
        [UIView animateWithDuration:0.3 animations:^{
            self.photoView.frame = CGRectMake(0, (IsIOS7?20:0)-90, 320, 90);
        }completion:^(BOOL finished) {
        }];
        
    }
}

//从相册选择图片后操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
    //NSLog(@"%@",info);
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self saveImage:image withName:@"currentImage.png"];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
    NSLog(@"%@",fullPath);
    [self.personImage setImage:[UIImage imageWithContentsOfFile:fullPath] ];
    double n = 320/self.personImage.image.size.width;
    self.personImage.frame = CGRectMake(0, 44+(IsIOS7?20:0), 320, self.personImage.image.size.height*n);
    //将图片保存到disk
    //UIImageWriteToSavedPhotosAlbum(currentImage, nil, nil, nil);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

完整DEMO下载地址:http://download.csdn.net/detail/u011918080/6975279

你可能感兴趣的:(iOS开发)