效果图:
示例代码:
IWLoadingProgressView *loadProgress = [IWLoadingProgressView progressView]; loadProgress.frame = CGRectMake(0, 0, AdaptedWidth(100), AdaptedHeight(100)); loadProgress.progress = 0.0; loadProgress.center = self.view.center; [self.view addSubview:loadProgress];
自定义控件代码:
@interface IWLoadingProgressView : UIView @property (nonatomic,assign) CGFloat progress;
#import "IWLoadingProgressView.h" static const CGFloat WLoadingProgressViewItemMargin = 10; @implementation IWLoadingProgressView - (instancetype)initWithFrame:(CGRect)frame self = [super initWithFrame:frame]; self.backgroundColor = [UIColor colorWithRed:240/255.0 green:240/255.0 blue:240/255.0 alpha:1.0]; self.layer.cornerRadius = 5; self.clipsToBounds = YES; - (void)setProgress:(CGFloat)progress [self removeFromSuperview]; - (void)drawRect:(CGRect)rect CGContextRef context = UIGraphicsGetCurrentContext(); CGFloat centerX = rect.size.width * 0.5; CGFloat centerY = rect.size.height * 0.5; CGContextSetLineWidth(context, 4); CGFloat to = M_PI * 2 * _progress; CGFloat radius = MIN(centerX, centerY) - WLoadingProgressViewItemMargin; CGContextAddArc(context, centerX, centerY, radius, 0, to, 0); CGContextStrokePath(context); CGContextAddArc(context, centerX, centerY, radius, to, M_PI * 2, 0); [[UIColor whiteColor] set]; CGContextStrokePath(context); NSMutableDictionary *attributes = [NSMutableDictionary dictionary]; attributes[NSFontAttributeName] = [UIFont systemFontOfSize:14.0]; attributes[NSForegroundColorAttributeName] = [UIColor colorWithRed:234/255.0 green:186/255.0 blue:133/255.0 alpha:1.0]; NSInteger p = _progress * 100; NSString *showText = [NSString stringWithFormat:@"%ld",(long)p]; showText = [showText stringByAppendingString:@"%"]; [self setCenterProgressText:showText withAttributes:attributes]; - (void)setCenterProgressText:(NSString *)text withAttributes:(NSDictionary *)attributes CGFloat centerX = self.frame.size.width * 0.5; CGFloat centerY = self.frame.size.height * 0.5; NSAttributedString *attrStr = nil; if (attributes[NSFontAttributeName]) { strSize = [text sizeWithAttributes:@{NSFontAttributeName:attributes[NSFontAttributeName]}]; attrStr = [[NSAttributedString alloc] initWithString:text attributes:attributes]; strSize = [text sizeWithAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[UIFont systemFontSize]]}]; attrStr = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:[UIFont systemFontSize]]}]; CGFloat strX = centerX - strSize.width * 0.5; CGFloat strY = centerY - strSize.height * 0.5; [attrStr drawAtPoint:CGPointMake(strX, strY)]; return [[self alloc] init];
|