標籤:
1、圖片浮水印
//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