在iPhone应用程序Roambi中,所显示的饼图可以设置为与用户一起旋转,就像旋转光盘一样.我们可以坚持并做很多事情.
有人提到Roambi应用程序是使用核心图库开发的:
如何操作使用Core plot开发的饼图?
快速浏览Core Plot源代码可以看出它CPPieChart的继承如下所示:
所以你可以看到,最后,CPPieChart只是一个重度子类CALayer.我可能在这里完全不正确,但没有任何迹象表明这不能像其他任何动画一样CALayer.请尝试以下代码将图层旋转360度:
CABasicAnimation *rotation = [CABasicAnimation animationWithKeyPath:@"transform"];
CATransform3D transform = CATransform3DMakeRotation(DegreesToRadians(360), 0, 0, 1);
rotation.toValue = [NSValue valueWithCATransform3D:transform];
rotation.duration = 10.0f;
[pieChart addAnimation:rotation forKey:@"rotation"];
Run Code Online (Sandbox Code Playgroud)
如果你可以使这个工作,那么只需要从加速度计读取值并将它们转换为旋转角度.
对于简单的饼图,即使使用上述动画,Core Plot也不是必需的.如果您只想要Core Plot解决方案,请忽略此答案.但是,这是一个简单的解决方案,不需要外部包甚至任何框架.
创建一个名为PieChartView的UIView.在PieChartView.h中:
#import <UIKit/UIKit.h>
@interface PieChartView : UIView {
float zeroAngle;
NSMutableArray *valueArray;
NSMutableArray *colorArray;
}
@property (nonatomic) float zeroAngle;
@property (nonatomic, retain) NSMutableArray *valueArray;
@property (nonatomic, retain) NSMutableArray *colorArray;
@end
Run Code Online (Sandbox Code Playgroud)
然后在PieChartView.m中执行:
#import "PieChartView.h"
@implementation PieChartView
@synthesize zeroAngle;
@synthesize valueArray, colorArray;
- (id)initWithFrame:(CGRect)frame {
if ((self = [super initWithFrame:frame])) {
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
// DETERMINE NUMBER OF WEDGES OF PIE
int wedges = [valueArray count];
if (wedges > [colorArray count]) {
NSLog(@"INSUFFICENT COLORS FOR PIE CHART: Please add %d additional colors.",wedges-[colorArray count]);
for (int i=[colorArray count] ; i<wedges ; ++i) {
[colorArray addObject:[UIColor whiteColor]];
}
}
// DETERMINE TOTAL VOLUME OF PIE
float sum = 0.0;
for (int i=0; i<wedges ; ++i) {
sum += [[valueArray objectAtIndex:i] floatValue];
}
float frac = 2.0*M_PI/sum;
// DETERMINE CENTER AND MAXIMUM RADIUS OF INSCRIBED CIRCLE
int center_x = rect.size.width/2.0;
int center_y = rect.size.height/2.0;
int radius = (center_x > center_y ? center_x : center_y);
// DRAW WEDGES CLOCKWISE FROM POSITIVE X-AXIS
float startAngle=zeroAngle;
float endAngle=zeroAngle;
for (int i=0; i<wedges; ++i) {
startAngle = endAngle;
endAngle += [[valueArray objectAtIndex:i] floatValue]*frac;
[[colorArray objectAtIndex:i] setFill];
CGContextMoveToPoint(context, center_x, center_y);
CGContextAddArc(context, center_x, center_y, radius, startAngle, endAngle, 0);
CGContextClosePath(context);
CGContextFillPath(context);
}
}
- (void)dealloc {
[valueArray release];
[colorArray release];
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)
现在,您可以以任何方式将float zeroAngle绑定到加速度计,以实现所需的动画.