使用场景举例,玩过微博发表长文章的应该都知道,可以选择封面图,这个封面图是有一定比例的,例如375/280,那我们怎么控制我们选择出来的图片一定是这比例呢,那就是截取这一比例的部分图片,有兴趣的朋友可以去微博看一下效果,下面我们来说一下实现方案.
需要调用的相册的控制器内代码
/**注意!控制器需实现相应代理*/
-(void)chooseImg {
UIImagePickerController *pc = [[UIImagePickerController alloc]init];
pc.delegate = self;
[pc setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
[pc setModalPresentationStyle:UIModalPresentationFullScreen];
[pc setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
[pc setAllowsEditing:YES];
[self presentViewController:pc animated:YES completion:nil];
}
//实现此方法,给系统相册增加方法
- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
if (navigationController.viewControllers.count == 3)
{
Method method = class_getInstanceMethod([self class], @selector(drawRect:));
class_replaceMethod([[[[navigationController viewControllers][2].view subviews][1] subviews][0] class],@selector(drawRect:),method_getImplementation(method),method_getTypeEncoding(method));
}
}
//我们需要的截取框(比例根据实际需要设置,此处为 375:280)
-(void)drawRect:(CGRect)rect
{
CGContextRef ref = UIGraphicsGetCurrentContext();
CGContextAddRect(ref, rect);
CGFloat h = (APP_WIDTH * 280) / 375;
CGContextAddRect(ref, CGRectMake(0, (APP_HEIGHT - h) * 0.5 , APP_WIDTH, h));
[[UIColor colorWithRed:0 green:0 blue:0 alpha:0.5]setFill];
CGContextDrawPath(ref, kCGPathEOFill);
CGContextAddRect(ref, CGRectMake(0, (APP_HEIGHT - h) * 0.5 , APP_WIDTH, h));
[[UIColor whiteColor]setStroke];
CGContextStrokePath(ref);
}
//当得到照片或者视频后,调用该方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
NSLog(@"Picker returned successfully.");
NSLog(@"%@", info);
if (_isHeadClick) {
NSLog(@"----%s",__func__);
[picker dismissViewControllerAnimated:YES completion:nil];
UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
NSLog(@"==image==%@",NSStringFromCGSize(image.size));
//生成最终图片
UIImage *image2 = [UIImage imagewithImage:image];
}
}
UIImage+cutImage
.h文件
#import <UIKit/UIKit.h>
@interface UIImage (cutImage)
//将图片截成方形图片
+ (UIImage *)imagewithImage:(UIImage *)image;
@end
.m文件
#import "UIImage+cutImage.h"
@implementation UIImage (cutImage)
+ (UIImage *)imagewithImage:(UIImage *)image
{
CGFloat width = image.size.width;
//因为实际的截图还是系统的剪切框截出来的图片,所以这里处理成我们自己实际需要的比例
CGFloat resultH = width * 280 / 375;
CGFloat height = image.size.height;
CGRect rect = CGRectMake(0, (height - resultH) * 0.5, width, resultH);
CGImageRef imageRef = CGImageCreateWithImageInRect([image CGImage], rect);
UIImage *thumbScale = [UIImage imageWithCGImage:imageRef];
CGImageRelease(imageRef);
return thumbScale;
}
@end