IOS开发UI篇--使用CAShapeLayer实现一个音量大小动态改变的控件

来源:互联网 发布:网络操作系统课件 编辑:程序博客网 时间:2024/05/21 10:33

一、案例演示

对于实时显示语音音量大小的需求,发现很多人的实现方式通过预放置多张图进行切换进行完成的。这样的处理,不但会浪费App的资源存储空间,而且效率也不高。对于符合某一定规律动态改变的图形,我们也可以考虑通过代码的方式来实现。
演示图片

二、实现机制

描述
外部轮廓View主要控制显示大小和显示的圆角效果。内部的Layer主要控制动态显示的高度,虽然他是矩形的。但是当把该Layer加入到View中,而该View设置了

_dynamicView.clipsToBounds = YES;

。内部的Layer超过外部轮廓的部分,则会被切除掉。
如此说来,我们只需要动态改变内部Layer显示的高度,即可完成该效果显示。是不是很简单啊。。

三、实现代码

_dynamicView 表示外部轮廓的View。
_indicateLayer 表示内容动态显示的Layer。
实现动态改变的函数如下:

-(void)refreshUIWithVoicePower : (NSInteger)voicePower{    CGFloat height = (voicePower)*(CGRectGetHeight(_dynamicView.frame)/TOTAL_NUM);    [_indicateLayer removeFromSuperlayer];    _indicateLayer = nil;    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, CGRectGetHeight(_dynamicView.frame)-height, CGRectGetWidth(_dynamicView.frame), height) cornerRadius:0];    _indicateLayer = [CAShapeLayer layer];    _indicateLayer.path = path.CGPath;    _indicateLayer.fillColor = [UIColor whiteColor].CGColor;    [_dynamicView.layer addSublayer:_indicateLayer];}

四、联系方式

微博:新浪微博
博客:http://blog.csdn.net/yixiangboy
github:https://github.com/yixiangboy

3 0
原创粉丝点击