android view流星,刚学习安卓几个月,自己写了一个简单的自定义View

package com.hy.rpg.view;

import android.content.Context;

import android.content.res.Resources;

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.graphics.Canvas;

import android.graphics.Paint;

import android.os.Handler;

import android.util.AttributeSet;

import android.view.View;

import com.hy.rpg.R;

import com.hy.rpg.utils.Utils;

/**

* meteor view

*

* @author HY

*/

@SuppressWarnings("ALL")

public class MeteorView   extends View {

/*message of view   stop*/

private static   final int VIEW_STOP = 0;

/*screen size*/

protected int   width, height;

/*X and Y   coordinate*/

protected int   coordinateX, coordinateY;

/*Y coordinate   max value*/

protected int   maxY;

protected Paint   mPaint;

protected Bitmap   bitmap;

protected   Resources res;

/*handle the   massage when this view will stop*/

private Handler   mHandler = new Handler() {

public   void handleMessage(android.os.Message msg) {

listener.viewStop(MeteorView.this);

}

};

public   MeteorView(Context context) {

this(context,   null);

}

public   MeteorView(Context context, AttributeSet attrs) {

this(context,   attrs, 0);

}

public   MeteorView(Context context, AttributeSet attrs, int defStyleAttr) {

super(context,   attrs, defStyleAttr);

res   = this.getResources();

height   = Utils.getHeight(res);

width   = Utils.getWidth(res);

maxY   = height - Utils.getDpSize(100, res);

/*generate   random coordinate in screen*/

coordinateX   = Utils.getRanNum(width * 3 / 4) + (width / 4);

coordinateY   = Utils.getRanNum(height / 2);

mPaint   = new Paint();

bitmap   = BitmapFactory.decodeResource(res, R.mipmap.ic_meteor);

new   MeteorThread().start();

}

@Override

protected void   onDraw(Canvas canvas) {

super.onDraw(canvas);

canvas.drawBitmap(bitmap,   coordinateX, coordinateY, mPaint);

}

class   MeteorThread extends Thread {

@Override

public   void run() {

boolean   flag = true;

int   rate = CommonUtils.getRanNum(7) + 3;

while   (flag) {

coordinateX   -= rate;

coordinateY   += rate;

if   (coordinateX <= 0 || coordinateY >= maxY) {

flag   = false;

mHandler.sendEmptyMessage(VIEW_STOP);

}

try   {

Thread.sleep(20);

}   catch (InterruptedException e) {

e.printStackTrace();

}

postInvalidate();

}

}

}

protected   OnViewStopListener listener;

public void   setOnViewStopListener(OnViewStopListener listener) {

this.listener   = listener;

}

/**

* view stop   listener

*

* @author   HY

*/

public interface OnViewStopListener {

void viewStop(View view);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值