使用drawBitmap繪製圖片

用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"/>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章