package com.example.yuanxingjindutiao;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by Administrator on 2017/11/30,0030.
* 自己创建一个继承view的方法
*/
public class MyView extends View {
private int progress = 0;
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
if (msg.what == 0){
if (progress < 100){
progress ++;
//重新绘制
postInvalidate();
sendEmptyMessageDelayed(0,100);
}
}
}
};
public MyView(Context context) {
super(context);
}
public MyView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//定义画笔
Paint paint = new Paint();
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.RED);
paint.setStrokeWidth(1);
paint.setAntiAlias(true);
// 绘制圆圈,进度条背景
// canvas.drawCircle(cx,cy,100,paint);
canvas.drawCircle(getMeasuredWidth()/2,getMeasuredHeight()/2,getMeasuredWidth()/2,paint);
RectF rectF = new RectF(0,0,getMeasuredWidth(),getMeasuredHeight());
paint.setColor(Color.GREEN);
paint.setStrokeWidth(5);
//画圆弧....360...100 progress
canvas.drawArc(rectF,-90,360*progress/100,false,paint);
String text = progress+"%";
//设置文字的大小,需要在测量之前
paint.setTextSize(40);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(1);
paint.setStyle(Paint.Style.FILL);
Rect rect = new Rect();
//测量
paint.getTextBounds(text,0,text.length(),rect);
//画文字
canvas.drawText(text,getMeasuredWidth()/2-rect.width()/2,getMeasuredHeight()/2+rect.height()/2,paint);
}
public void start(){
handler.sendEmptyMessageDelayed(0,10);
}
}
布局中 将自己写的view方法放到布局中;
//main方法里
public class MainActivity extends AppCompatActivity {
private MyView myView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//通过id找到这个方法让他启动
myView = findViewById(R.id.mv);
myView.start();
}
}