iOS 画图讲解2
Posted iOS软件开发之路
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iOS 画图讲解2相关的知识,希望对你有一定的参考价值。
//layer上下文只能显示在drawRect里
//当开启上下文时,绘制图形即可在viewDidLoad中实现
//位图的上下文
//UIGraphicsBeginImageContext()仅适用于非retina屏
//开启位图上下文
size:位图的尺寸
opaque:不透明是yes,透明就是no
scale:是否缩放上下文
UIGraphicsBeginImageContextWithOptions(image.size, NO, 0);
//绘制原始图片
[image drawAtPoint:CGPointZero];
[image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
//第一种
NSString * info = @"@大欢";
NSDictionary * dict = @{NSForegroundColorAttributeName:[UIColor whiteColor],
NSFontAttributeName:[UIFont systemFontOfSize:30]};
[info drawAtPoint:CGPointMake(120, 200) withAttributes:dict];
//第二种
UIBezierPath * path = [UIBezierPath bezierPathWithRect:CGRectMake(100, 100, 100, 100)];
[[UIColor redColor] set];
[path fill];
//第三种
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(ctx, 20, 20);
CGContextAddLineToPoint(ctx, 40, 40);
CGContextStrokePath(ctx);
//生成一张新的图片,从位图上下文获取
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//关闭图片上下文
UIGraphicsEndImageContext();
self.imageView.image = newImage;
2、图片等比例缩小
操作 写在 通过上下文获取图片 之前
UIImage * image = [UIImage imageNamed:@"huoyanshan.jpg"];
CGFloat newImageWH = image.size.height;
//开启位图上下文
UIGraphicsBeginImageContextWithOptions(CGSizeMake(newImageWH, newImageWH), NO, 0);
UIBezierPath * path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, newImageWH, newImageWH)];
//添加剪切
[path addClip];
//绘图
[image drawAtPoint:CGPointZero];
//通过上下文获取图片
UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//关闭上下文
UIGraphicsEndImageContext();
self.imageView.image = newImage;
3、画线
//纯代码执行的第一个方法
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setUp];
}
return self;
}
//故事板执行的第一个方法
- (void)awakeFromNib {
[self setUp];
}
4、相册
//保存到手机相册
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//创建相册
UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
<UINavigationControllerDelegate, UIImagePickerControllerDelegate>写两个协议
imagePicker.delegate = self;
//UIImagePickerControllerSourceTypePhotoLibrary 相册
//UIImagePickerControllerSourceTypeCamera 相机
imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//允许编辑
imagePicker.allowsEditing = YES;
[self presentViewController:imagePicker animated:YES completion:nil];
}
//相册选择完成的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
//编辑图片 如果allowsEditing为NO,image没有值
_drawView.image = info[UIImagePickerControllerEditedImage];
//原始图片
_drawView.image = info[UIImagePickerControllerOriginalImage];
[picker dismissViewControllerAnimated:YES completion:nil];
}
//取消选择
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
NSLog(@"取消选择");
[picker dismissViewControllerAnimated:YES completion:nil];
}
以上是关于iOS 画图讲解2的主要内容,如果未能解决你的问题,请参考以下文章