新项目有个需求是要按照百分比来切割一个圆形的图片,研究了一下午终于搞定了,代码如下:
.h文件:
#import <UIKit/UIKit.h>
@interface CWPercentImageView : UIView
///开始点,从圆的顶点开始
@property (nonatomic,assign) CGFloat startPoint;
///结束点 需要自己计算
@property (nonatomic,assign) CGFloat endPoint;
///如果isCLockwise==YES 则endPoint的范围为0~-2 如果为NO则范围为0~2
@property (nonatomic,assign) BOOL isClockwise;
@end
.m文件:
- (void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextMoveToPoint(context, self.bounds.size.width/2.0, self.bounds.size.height/2.0);
CGContextAddArc(context, self.bounds.size.width/2.0, self.bounds.size.height/2.0, self.bounds.size.width/2.0, _startPoint - M_PI/2.0, _endPoint, (int)_isClockwise);
UIColor*aColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"气泡遮罩"]];
CGContextSetFillColorWithColor(context, aColor.CGColor);
CGContextDrawPath(context, kCGPathFill);
CGImageRef mask = CGBitmapContextCreateImage(context);
CGContextClipToMask(context, rect, mask);
}
外部调用的时候这么做:
_percentImageView = [[CWPercentImageView alloc] initWithFrame:CGRectMake(0, 0, 169, 169)];
_percentImageView.backgroundColor = [UIColor clearColor];
_percentImageView.isClockwise = YES;
_percentImageView.startPoint = 0;
_percentImageView.endPoint = (-2 * 0.8) * M_PI - M_PI/2.0;
[image addSubview:_percentImageView];
0.8为80% yes表示是逆时针重绘图片~
最后的
_percentImageView.endPoint = (-2 * 0.8) * M_PI - M_PI/2.0;是-2不是-22,不知道为什么会变成-22.。。。