自定义带动画效果的矩形条控件
项目的原因需要一个带动画效果的矩形条,因为progressbar需要设置主题(有些主题下为圆圈)而且没有自带动画,所以自己写了个控件。
下面是实现方法:
1.继承自View
public class SingleBarChart extends View
2.成员变量
private Paint mPaint;
private int mBarColor;
private int percentTotal;
private boolean canAnimate = false;
BarAnimation anim;
private float per=0;
private int iDisplayWidth, iDisplayHeight;
private String mText = "";
mPaint
画笔,mBarColor
3.构造函数
public SingleBarChart(Context context) {
this(context, null, 0);
}
public SingleBarChart(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SingleBarChart(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.SingleBarChart);
mBarColor = a.getColor(R.styleable.SingleBarChart\_barColor ,0xFF409be4);
percentTotal = a.getInteger(R.styleable.SingleBarChart\_percent, 0);
CharSequence sequence = a.getText(R.styleable.SingleBarChart\_text);
if(sequence != null){
mText = sequence.toString();
}
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(mBarColor);
anim = new BarAnimation();
anim.setDuration(1000);
if( percentTotal !=0 ){
if(canAnimate){
this.startAnimation(anim);
}else{
per = 1.0f;
}
}
}
4.绘制矩形
@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
mPaint.setColor(mBarColor);
canvas.drawRect(0, 0, iDisplayWidth* ((float) percentTotal /100)* per, iDisplayHeight, mPaint);
mPaint.setColor(0xFFE6E6E6);
canvas.drawRect(iDisplayWidth* ((float) percentTotal /100)* per, 0, iDisplayWidth, iDisplayHeight, mPaint);
canvas.drawText(mText, 0,(iDisplayHeight+iDisplayHeight/10 *7)/2, mPaint);
}
需要绘制两个矩形条,一个为背景,设置为很浅的灰色,一个为进度,可以自行设置颜色。
5.自定义动画
public class BarAnimation extends Animation {
/**
* Initializes expand collapse animation, has two types, collapse (1) and expand (0).
* @param view The view to animate
* @param type The type of animation: 0 will expand from gone and 0 size to visible and layout size defined in xml.
* 1 will collapse view and set to gone
*/
public BarAnimation() {
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
super.applyTransformation(interpolatedTime, t);
if (interpolatedTime < 1.0f) {
per = interpolatedTime;
postInvalidate();
} else {
per = 1.0f;
}
}
}
applyTransformation
方法可以得到一个由0逐渐变化到1的时间函数,因此可以利用这个值的变化来设置矩形条动画进度。