使用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"/>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值