你可能不会让你的派片边缘完全没有裂缝。最简单的解决方案是不要尝试。
而不是让你的馅饼切片在边缘相遇,使它们重叠。绘制第一个切片作为一个完整的光盘:
再画第二层作为一个完整的盘,除了第一层的正确面积:
然后绘制第三片作为全盘,除了前两片的正确区域:
等等:
这里是我的代码:
#import "PieView.h"
@implementation PieView {
NSMutableArray *slices;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)layoutSubviews {
[super layoutSubviews];
[self layoutSliceLayers];
}
- (void)layoutSliceLayers {
if (slices == nil) {
[self createSlices];
}
[slices enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[self layoutSliceLayer:obj index:idx];
}];
}
static const int kSliceCount = 5;
- (void)createSlices {
slices = [NSMutableArray arrayWithCapacity:kSliceCount];
for (int i = 0; i < kSliceCount; ++i) {
[slices addObject:[self newSliceLayerForIndex:i]];
}
}
- (CAShapeLayer *)newSliceLayerForIndex:(int)i {
CAShapeLayer *layer = [CAShapeLayer layer];
layer.fillColor = [UIColor colorWithWhite:(CGFloat)i/kSliceCount alpha:1].CGColor;
[self.layer addSublayer:layer];
return layer;
}
- (void)layoutSliceLayer:(CAShapeLayer *)layer index:(int)index {
layer.position = [self center];
layer.path = [self pathForSliceIndex:index].CGPath;
}
- (CGPoint)center {
CGRect bounds = self.bounds;
return CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds));
}
- (UIBezierPath *)pathForSliceIndex:(int)i {
CGFloat radius = [self radius];
CGFloat fudgeRadians = 5/radius;
UIBezierPath *path = [UIBezierPath bezierPathWithArcCenter:CGPointZero
radius:radius startAngle:2 * M_PI * i/kSliceCount
endAngle:2 * M_PI clockwise:YES];
[path addLineToPoint:CGPointZero];
[path closePath];
return path;
}
- (CGFloat)radius {
CGSize size = self.bounds.size;
return 0.9 * MIN(size.width, size.height)/2;
}
@end
非常感谢您的答复,罗布。我确实在某个时候尝试了这个解决方案,并且看到来自较暗的底层的抗锯齿伪像正在反锯齿到背景中。它出现在饼图周围的一个微妙的黑色边缘,在较浅的彩色切片的外边缘处尤为明显。我所描述的径向填充解决方案似乎运作良好。 – Aaron
@Aaron当你使用反锯齿时,你最终会在纯色的有效锯齿形状周围形成一圈颜色+ alpha像素。对于具有相同轮廓的多个形状执行此操作时,有效混叠的内部区域看起来不错,但防混叠区域将具有颜色(n)+ alpha重叠颜色(n-1)+ alpha重叠... color(0) +阿尔法。这解释了你所看到的效果。 –