上午自定义了一个公司logo的小动画,实现起来也稍简单,可以先看一下具体实现后的效果:
大体的实现过程,我大概了分了四个步骤:
1、实现外圆框
2、实现底部小尾巴
3、实现内圆折线
4、实现两个小箭头
具体我们就来代码实现吧:
自定义一个类,继承于View,实现其构造方法,在构造方法里,初始化画笔,等相关信息:
private void initView() {
mPaint = new Paint();
mPaint.setColor(0xFFEA4335);
mPaint.setStrokeWidth(2);
mPaint.setStrokeCap(Paint.Cap.ROUND);
oval = new RectF();
oval.left = 100;
oval.top = 100;
oval.right = 400;
oval.bottom = 400;
handler.sendEmptyMessageDelayed(SEND_WHAT, 500);
}
这里,我发了一个Handler,目的主要做一个定时,更新绘制View,handler里主要逻辑:
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == SEND_WHAT) {
if (end) {
invalidate();
handler.sendEmptyMessageDelayed(SEND_WHAT, 80);
} else {
handler.removeMessages(SEND_WHAT);
}
}
}
};
end是一个开关,一开始为true,当view绘制完后,赋值为false,移除定时。
下面就是onDraw方法里进行绘制了,下面这个方法,主要绘制了外圆框,drawTail方法是绘制底部小尾巴,drawCenter是绘制内圆折线。
/**
* 绘制Logo
*/
private void drawLogo() {
if (cricleSize > -295) {
drawCricle(cricleSize);
} else {
drawCricle(-295);
tailSize += 5;
float tailLenth = 365 + tailSize;
if (tailLenth < 415) {
drawTail(tailLenth);
} else {
drawTail(415);
drawCenter();
}
}
//每次递减10,逆时针画
cricleSize = cricleSize - 10;
}
/**
* 绘制外圆
*/
private void drawCricle(float size) {
mPaint.setAntiAlias(true); //设置画笔为无锯齿
mPaint.setColor(0xFFEA4335); //设置画笔颜色
mCanvas.drawColor(Color.WHITE); //白色背景
mPaint.setStrokeWidth((float) 30.0); //线宽
mPaint.setStyle(Paint.Style.STROKE);
mCanvas.drawArc(oval, 290, size, false, mPaint); //绘制圆弧
}
/**
* 绘制右下角的尾巴
*/
private void drawTail(float size) {
mCanvas.drawLine(365, 365, size, size, mPaint);
}
/**
* 绘制中间的折线及箭头
*/
private void drawCenter() {
centerLine1 += 5;
centerLine1_1 += 6;
float x = 115 + centerLine1;
float y = 310 - centerLine1_1;
if (centerLine1 <= 75) {
drawCenterRect1(x, y);
} else {
drawCenterRect1(190, 220);
centerLine2 += 5;
float x1 = 195 + centerLine2;
float y1 = 215 + centerLine2;
if (x1 < 250) {
drawCenterRect2(x1, y1);
} else {
drawCenterRect2(250, 270);
centerLine3 += 5;
centerLine4 += 5;
float sizeX = 250 + centerLine3;
float sizeY = 270 - centerLine4;
if (sizeX <= 380) {
drawCenterRect3(sizeX, sizeY);
} else {
drawCenterRect3(380, 140);
//绘制箭头
mCanvas.drawLine(350, 130, 380, 140, mPaint);
mCanvas.drawLine(385, 145, 390, 180, mPaint);
end = false;
}
}
}
}
/**
* 绘制圆内第一条线
*/
private void drawCenterRect1(float x, float y) {
mCanvas.drawLine(115, 310, x, y, mPaint);
}
/**
* 绘制圆内第二条线
*/
private void drawCenterRect2(float x, float y) {
mCanvas.drawLine(195, 215, x, y, mPaint);
}
/**
* 绘制圆内第三条线
*/
private void drawCenterRect3(float x, float y) {
mCanvas.drawLine(250, 270, x, y, mPaint);
}
很简单的一个小Demo,主要就是自定义View的一些常见东西。完整的代码,关注左侧二维码,发送“小动画”三个字就会推送给您。