Canvas基础

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;

public class MainActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyView(this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    class MyView extends View {
        Canvas mCanvas;
        Bitmap mBitmap;
        Paint mPaint;
        float movex, movey;
        float X_r, Y_r;

        public MyView(Context context) {
            super(context);
            init();
        }

        public void init() {
            mBitmap = Bitmap.createBitmap(240, 300, Config.ARGB_8888);
            mCanvas = new Canvas(mBitmap);
            mBitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.studycenter_userinfo_back);
            X_r = -mBitmap.getWidth();
            Y_r = -mBitmap.getHeight();
            mPaint = new Paint();
            mPaint.setColor(0xFFFFFFFF);
        }

        protected void onDraw(Canvas canvas) {
            canvas.drawBitmap(mBitmap, X_r, Y_r, mPaint);
            System.out.println("onDraw");
            super.onDraw(canvas);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {
            // 点击时的(x,y),记录初始位置
            case MotionEvent.ACTION_DOWN:
                Animation alphaAnimation = new AlphaAnimation(0.1f, 1.0f); 
                alphaAnimation.setDuration(500);
                this.startAnimation(alphaAnimation);
                movex = mBitmap.getWidth() / 2;
                movey = mBitmap.getHeight() / 2;
                X_r = x - movex;
                Y_r = y - movey;
                mPaint.setAlpha(255);
                invalidate();
                break;
            // 移动时更新(x,y),同时更新图片
            case MotionEvent.ACTION_MOVE:
                movex = mBitmap.getWidth() / 2;
                movey = mBitmap.getHeight() / 2;
                X_r = x - movex;
                Y_r = y - movey;
                invalidate();
                break;
            // 弹起时更新(x,y),并记录位置
            case MotionEvent.ACTION_UP:
                mPaint.setAlpha(0);
                invalidate();
                break;
            }
            return true;
        }
    }
}

posted on 2012-10-27 17:14  南瓜饼  阅读(197)  评论(0编辑  收藏  举报

导航