iphone 图表抖动效果实现-左上角小黑叉实习(层的使用)
这里图表简单的用一个红色的视图代替,左上角的小黑叉是新建了一个层,完全是画上去的

下面是一些实现代码
首先在.h文件中定义一个 CALayer *closeLayer; 这就是在图表晃动的时候左上角的黑叉的层对象
在.m文件中
这个方法返回一个中间没有叉的层,只有一个白色的边框
-(CALayer*)closeBoxLayer {
CGColorRef white =[UIColor whiteColor].CGColor;
CGColorRef black =[UIColor blackColor].CGColor;
CALayer *layer = [CALayer layer];
[layer setFrame:CGRectMake(-5.0,-5.0, 30.0, 30.0)];
[layer setBackgroundColor:black];
[layer setShadowColor:black];
[layer setShadowOpacity:1.0];
[layer setShadowRadius:5.0];
[layer setBorderColor:white];
[layer setBorderWidth:3];
[layer setCornerRadius:15];
[layer setDelegate:self];
return layer;
}
注意 一定要设置 layer的delegate
在button方法中
- (IBAction)action:(id)sender {
[self.block.layer addSublayer:closeLayer];
//这行代码是为了调用drawLayer
[closeLayer setNeedsDisplay];
[self.block.layer addAnimation:[self shakeAnimation] forKey:nil];
}
drawLayer方法
- (void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context {
CGMutablePathRef path = CGPathCreateMutable();
// 下面两行代码创建的路径是一个白色的叉
CGPathMoveToPoint(path,NULL,10.0f,10.f); CGPathAddLineToPoint(path, NULL, 20.0, 20.0); // Set the second point and add a line
CGPathMoveToPoint(path,NULL,10.0f,20.f); CGPathAddLineToPoint(path, NULL, 20.0, 10.0);
CGColorRef white = [UIColor whiteColor].CGColor;
CGContextSetStrokeColorWithColor(context, white); // Start drawing the path
CGContextBeginPath(context);
CGContextAddPath(context, path);
// Set the line width to 3 pixels
CGContextSetLineWidth(context, 3.0);
CGContextStrokePath(context);
}
最后看一下 图表抖动的方法 shakeAnimation
- (CAAnimation*)shakeAnimation; {
CAKeyframeAnimation * animation; animation = [CAKeyframeAnimation
animationWithKeyPath:@"transform.rotation.z"];
[animation setDuration:0.2];
[animation setRepeatCount:10000];
// Try to get the animation to begin to start with a small offset // that makes it shake out of sync with other layers. srand([[NSDate date] timeIntervalSince1970]);
//下面两行代码的作用是 规定一个随机的开始时间,即动画的其实状态是随机的
// float rand = (float)random();
// [animation setBeginTime: CACurrentMediaTime() + rand * .0000000001];
NSMutableArray *values = [NSMutableArray array]; // Turn right
[values addObject:DegreesToNumber(-2)]; // Turn left
[values addObject:DegreesToNumber(2)]; // Turn right
[values addObject:DegreesToNumber(-2)]; // Set the values for the animation
[animation setValues:values]; return animation;
}
CGFloat DegreesToRadians(CGFloat degrees) {
return degrees * M_PI / 180;
}
NSNumber* DegreesToNumber(CGFloat degrees) {
return [NSNumber numberWithFloat: DegreesToRadians(degrees)];
}
在这个例子中 图表抖动主要利用了 transform.rotation.z 这个关键字 创建了一个 CAKeyframeAnimation 实例,然后利用values属性 不断改变度数来实现。
而关闭时候的黑叉主要利用了层的绘制。
在drawLayer中的 创建path的时候 所用的四个点的坐标是相对于closeLayer来说的。
浙公网安备 33010602011771号