安卓开发之自定义动画控件BatteryView(电池加载动画)

前几天在网页上看到一个不错的加载动画View后,想将它在安卓上实现一遍。效果如下,很简单。

这里写图片描述

因为控件实现动画时,更新视图的频率会很高。为了减少内存的占用,决定使用SurfaceView来实现。

一、对控件的测量

使用的规则是:当控件的宽/高不是固定时,宽/高的大小为默认的宽高+padding值。反之,使用传递过来的宽高。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
    int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
    int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
    int modeHeight = MeasureSpec.getMode(heightMeasureSpec);

    if(modeWidth == MeasureSpec.AT_MOST || modeWidth == MeasureSpec.UNSPECIFIED ){
        sizeWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,bwidth,getContext().getResources().getDisplayMetrics());
        sizeWidth += getPaddingLeft()+getPaddingRight();
    }
    if(modeHeight == MeasureSpec.AT_MOST || modeHeight == MeasureSpec.UNSPECIFIED ){
        sizeHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,bheight,getContext().getResources().getDisplayMetrics());
        sizeHeight += getPaddingBottom()+getPaddingTop();
    }

    setMeasuredDimension(sizeWidth,sizeHeight);

}

二、对控件的绘制

private void drawView(Canvas canvas){

    // 绘制背景图
    canvas.drawColor(backgroundColor);

    // 绘制电池框
    canvas.drawRoundRect(SrectF,bRadius,bRadius,paintS);

    // 绘制电池的小点
    canvas.drawRect(centerX+bwidth/2-distance,centerY-bheight/4,centerX+bwidth/2,centerY+bheight/4,paintF);

    // 更新电池填充的右边大小
    FrectF.right =  FrectF.left+varyInnerWidth;

    // 绘制电池的填充
    canvas.drawRoundRect(FrectF,bRadius,bRadius,paintF);

    // 根据不同情况,修改电池填充的右边大小
    if(SrectF.left+varyInnerWidth>centerX+bwidth
  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值