【发布时间】:2014-06-04 20:42:54
【问题描述】:
我需要一个派生自UIView 的类,它通过填充越来越大的圆扇区来表示进度(随着进度从0 变为1,它的角度应该增加2 PI)。这就像UIProgressView 的循环版本。
下面的代码还不能很好地完成这项工作:它会生成越来越多的小扇区,以闪烁的斑马图案堆叠。据推测,代码将其坐标与 UIView flipping 其坐标系、CGContextAddArc 的(显然)“顺时针”的反直觉定义等混淆了。
不当行为的原因是什么?如何解决?
#define PERCENTAGE_TO_RADIANS(PERCENTAGE) ((PERCENTAGE) * 2 * M_PI - M_PI_2)
- (void)drawRect:(CGRect)rect
{
NSAssert(!self.opaque, nil);
NSAssert(!self.clearsContextBeforeDrawing, nil);
CGSize size = self.bounds.size;
CGPoint center = [self.superview convertPoint:self.center toView:self];
NSAssert(size.width == size.height, nil);
NSAssert((self.progress >= 0) && (self.progress <= 1), nil);
NSAssert(PERCENTAGE_TO_RADIANS(0 ) == -M_PI_2 , nil); // 0% progress corresponds to north
NSAssert(PERCENTAGE_TO_RADIANS(0.25) == 0 , nil); // 25% progress corresponds to east
NSAssert(PERCENTAGE_TO_RADIANS(0.5 ) == M_PI_2 , nil); // 50% progress corresponds to south
NSAssert(PERCENTAGE_TO_RADIANS(0.75) == M_PI , nil); // 75% progress corresponds to west
NSAssert(PERCENTAGE_TO_RADIANS(1 ) == 3 * M_PI_2, nil); // 100% progress corresponds to north
CGFloat x = center.x;
CGFloat y = center.y;
CGFloat radius = size.width / 2.0;
CGFloat startAngle = self.lastAngle;
CGFloat endAngle = PERCENTAGE_TO_RADIANS(self.progress);
int clockwise = 0;
if (self.progress > 0) {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetFillColorWithColor(context, self.sectorTintColor.CGColor);
CGContextSetLineWidth(context, 1);
NSAssert(startAngle <= endAngle, nil);
CGContextMoveToPoint(context, x, y);
CGContextAddArc(context, x, y, radius, startAngle, endAngle, clockwise);
CGContextClosePath(context);
CGContextFillPath(context);
CGContextRestoreGState(context);
}
self.lastAngle = endAngle;
}
【问题讨论】:
标签: ios uiview uikit cgcontext uiprogressview