自定义View二(加入线程,实现绘制图形动态化)

来源:互联网 发布:剑灵男刺客捏脸数据图 编辑:程序博客网 时间:2024/06/07 03:41

动态那么肯定就需要一个线程里面加一个循环,当然还需要变量!
public class animalView extends View {

protected MyThread mThread;private Paint mPaint;private float moveX = 0;private RectF mRectF = new RectF(0, 40, 60, 100);  //矩形方阵,如果这里绘制的是正方形那么绘制出来的就是圆形,如果是长方形绘制出来的就是椭圆形!private float sweepAngle = 0;private Random mRand = new Random();public animalView(Context context) {    super(context);}public animalView(Context context, AttributeSet attrs) {    super(context, attrs);}@Overrideprotected void onDraw(Canvas canvas) {    mPaint = new Paint();    if (mThread == null) {        mThread = new MyThread();        mThread.start();    } else {        drawView(canvas);    }}public void drawView(Canvas canvas) {    mPaint.setTextSize(30);    int r = mRand.nextInt(256);    int g = mRand.nextInt(256);    int b = mRand.nextInt(256);    mPaint.setARGB(255, r, g, b); //随机产生颜色值!    canvas.drawText("我在不停的移动中", moveX, 30, mPaint);    canvas.drawArc(mRectF, 0, sweepAngle, true, mPaint);  //该方法其实就是在矩形里面根据角度的不断变化绘制一个圆!}protected class MyThread extends Thread {    @Override    public void run() {        super.run();        while (true) {            moveX = moveX + 1;            float textWitch = mPaint.measureText("我在不停的移动中"); //横向坐标的不断增加            if (moveX > getWidth()) {                moveX = 0 - textWitch;            }            sweepAngle = sweepAngle + 1;  //角度的不断增加            if (sweepAngle > 360) {                sweepAngle = 0;            }            try {                Thread.sleep(30);            } catch (InterruptedException e) {                e.printStackTrace();            }            postInvalidate();  //该方法会调用 onDraw(Canvas canvas)        }    }}

}
注释已经差不多了,其实还是要自己动手做一下就明白了,看看没什么用的!

0 0
原创粉丝点击