使用drawBitmap绘制图片

来源:互联网 发布:mysql 1267 编辑:程序博客网 时间:2024/05/18 00:43

用drawBitmap写了个会动的小僵尸
首先是图片资源
这里写图片描述

自定义View中代码如下

public class ZoombieView extends View {    private int width,height;    private int intervalW,intervalH;    private Paint bitmapPaint;    private Bitmap bitmap;    private Rect src;    private Rect dst;    private int currentW=0;    private int currentH=0;    private Handler handler=new Handler(){        @Override        public void handleMessage(Message msg) {            super.handleMessage(msg);            if (currentW<10&&currentH==0){                currentW++;                invalidate();                sendEmptyMessageDelayed(0,300);            }else if (currentW==10&&currentH==0){                currentH++;                currentW=0;                invalidate();                sendEmptyMessageDelayed(0,300);            }else if (currentW<10&&currentH==1){                currentW++;                invalidate();                sendEmptyMessageDelayed(0,300);            }        }    };    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);        width=w;        height=h;    }    public ZoombieView(Context context) {        this(context,null);    }    public ZoombieView(Context context, AttributeSet attrs) {        super(context, attrs);        initView();    }    private void initView() {        bitmapPaint=new Paint();        bitmapPaint.setAntiAlias(true);        bitmapPaint.setDither(true);        bitmapPaint.setFilterBitmap(true);        bitmap= BitmapFactory.decodeResource(getResources(), R.mipmap.zombie);        intervalW=bitmap.getWidth()/11;        intervalH=bitmap.getHeight()/2;    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        canvas.translate(width/2,height/2);        src=new Rect(intervalW*currentW,intervalH*currentH,intervalW*(currentW+1),intervalH*(currentH+1));        dst=new Rect(-intervalW/2,-intervalH/2,intervalW/2,intervalH/2);        canvas.drawBitmap(bitmap,src,dst,bitmapPaint);        if (currentW==0&&currentH==0){            handler.sendEmptyMessageDelayed(0,300);        }    }}

在布局中引用

<com.example.mytestapplication.widget.ZoombieView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerInParent="true"/>
原创粉丝点击