-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathUIImage+Mask.m
67 lines (47 loc) · 2.01 KB
/
UIImage+Mask.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//
// UIImage+Mask.m
// WithTrip
//
// Created by ZhouBin on 14-6-20.
// Copyright (c) 2014年 Zhou Bin. All rights reserved.
//
#import "UIImage+Mask.h"
@implementation UIImage (Mask)
// mask image
- (UIImage *)circleMaskImageWithDiameter:(CGFloat)diameter {
UIGraphicsBeginImageContext(CGSizeMake(diameter, diameter));
CGContextRef context = UIGraphicsGetCurrentContext();
UIGraphicsPushContext(context);
CGContextSetAllowsAntialiasing(context, YES);
//填充
CGContextMoveToPoint(context, 0, 0);
CGContextAddLineToPoint(context, diameter, 0);
CGContextAddLineToPoint(context, diameter, diameter);
CGContextAddLineToPoint(context, 0, diameter);
CGContextAddLineToPoint(context, 0, 0);
CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor);
CGContextFillPath(context);
//画圆
CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
CGContextFillEllipseInRect(context, CGRectMake(0, 0, diameter, diameter));
UIGraphicsPopContext();
UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return outputImage;
}
- (UIImage *)maskedImageWithMaskImage:(UIImage *)maskImage {
CGImageRef maskRef = maskImage.CGImage;
CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(maskRef),
CGImageGetHeight(maskRef),
CGImageGetBitsPerComponent(maskRef),
CGImageGetBitsPerPixel(maskRef),
CGImageGetBytesPerRow(maskRef),
CGImageGetDataProvider(maskRef), NULL, false);
CGImageRef masked = CGImageCreateWithMask([self CGImage], mask);
return [UIImage imageWithCGImage:masked];
}
- (UIImage *)circleImage {
UIImage *maskImage = [self circleMaskImageWithDiameter: self.size.width * 2];
return [self maskedImageWithMaskImage:maskImage];
}
@end