Android自定义一个动画

今天写一个简单的动画,让其旋转并且透明度变化,这个还是相对简单的。先看一下效果:



首先在res-values下新建一个attrs.xml,这个是自定义属性的。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="myViewaStyle">
        <attr name="color" format="color"></attr>
        <attr name="radius" format="dimension"></attr>
    </declare-styleable>
</resources>

接下来就是自定义一个view了,新建一个类继承View,

这个是添加自定义属性的,就不解释了,不懂得看一下鸿洋_大神写的Android 深入理解Android中的自定义属性

TypedArray typedArray = context.obtainStyledAttributes(attr, R.styleable.myViewaStyle);
if(typedArray != null){
    color = typedArray.getColor(R.styleable.myViewaStyle_color, Color.RED);
    minRadius = typedArray.getDimension(R.styleable.myViewaStyle_radius, 50);
    typedArray.recycle();
}

接下来主要就是画图了,我们可以看到这个view是由7个正六边形组成,一个在中间,六个在周边,只要知道中心点就可以画出正六边形。

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    cHeight = h / 2;
    cWidth = w / 2;
}
这个是得到屏幕的中心点的坐标,现在就可以画出中间的六边形,

Path mPath = new Path();
mPath.moveTo((float) (cWidth - Math.cos(mAngel * 0) * getMinRadius()), (float) (cHeight - Math.sin(mAngel * 0) * getMinRadius()));
for(int i = 1; i < 6 ;i ++){
    float mX = (float) (cWidth - Math.cos(mAngel * i) * getMinRadius());
    float mY = (float) (cHeight - Math.sin(mAngel * i) * getMinRadius());
    mPath.lineTo(mX,mY);
}
mPath.close();
canvas.drawPath(mPath,mPaint);
其余六个正六边形也是一样的

for(int i = 0; i < 6; i++){
    float x = (float) (cWidth - Math.sin(mAngel * i) * getMinRadius() * 2);
    float y = (float) (cHeight - Math.cos(mAngel * i) * getMinRadius() * 2);
    drwaMinPloygon(canvas, x, y);
}

private void drwaMinPloygon(Canvas canvas, float x, float y){

    Path path = new Path();
    path.moveTo((float) (x - Math.cos(mAngel * 0) * getMinRadius()), (float) (y - Math.sin(mAngel * 0) * getMinRadius()));
    for(int i = 1; i < 6 ;i ++){
        float mX = (float) (x - Math.cos(mAngel * i) * getMinRadius());
        float mY = (float) (y - Math.sin(mAngel * i) * getMinRadius());
        path.lineTo(mX,mY);
    }
    path.close();
    canvas.drawPath(path,mPaint);
}

所有的六边形现在就画好了,接下来主要就是动画,动画其实也是很简单的

ObjectAnimator rotate = ObjectAnimator.ofFloat(this, "rotation", 0f, 360f);
rotate.setRepeatCount(1000);
ObjectAnimator fadeInOut = ObjectAnimator.ofFloat(this, "alpha", 1f, 0.5f, 1f);
fadeInOut.setRepeatCount(1000);
AnimatorSet set = new AnimatorSet();
set.play(rotate).with(fadeInOut);
set.setDuration(2000);
set.start();
这样就可以实现view旋转和透明度变化循环1000,次,当然这个次数可以修改。动画不懂得建议看 郭霖大神的 Android属性动画完全解析(上),初识属性动画的基本用法

最后只要在xml文件里面定义好就可以了


这个动画可以作为loading加载框,虽然它很渣。有时间我会对它进行修改,添加更多的动画。这个view存在很多问题,有什么建议或者意见的希望大家告知,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值