码迷,mamicode.com
首页 > 其他好文 > 详细

双缓冲机制简介

时间:2016-03-26 18:42:35      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:

一.理解双缓冲机制

1.创建一个画板,和一个图片()

2.将图片设置为画板

3.之后画板将会在该图片上作画

4.之后再将图片放到View提供的画板上显示

二、实例(利用双缓冲机制的画板)

技术分享
public class DrawView extends View {
    private int view_width = 0;
    private int view_height = 0;
    private float prevX = 0;
    private float prevY = 0;
    private Path mPath;
    private Bitmap mCacheBitmap;
    private Canvas mCacheCanvas;
    private Paint mPaint;
    public DrawView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //获取屏幕的宽高
        WindowManager windowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        view_width = display.getWidth();
        view_height = display.getHeight();
        //创建双缓冲板
        mCacheBitmap = Bitmap.createBitmap(view_width, view_height, Bitmap.Config.ARGB_8888);//创建图片缓冲区
        mCacheCanvas = new Canvas(mCacheBitmap);//将该Canvas绘制到缓冲区中
        //创建Path
        mPath = new Path();
        //创建Paint
        mPaint = new Paint();
        mPaint.setStrokeWidth(3);
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float currentX = event.getX();
        float currentY = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_DOWN:
                prevX = currentX;
                prevY = currentY;
                mPath.moveTo(event.getX(), event.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                prevX = currentX;
                prevY = currentY;
                mPath.quadTo(prevX,prevY,currentX,currentY);
                break;
            case MotionEvent.ACTION_UP:
                mPath.reset();
                break;
        }
        mCacheCanvas.drawPath(mPath, mPaint);
        invalidate();
        //要将 return 改为 true 这样onTouchEvent()方法才会被执行
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        canvas.drawBitmap(mCacheBitmap,0,0,paint);
    }
}
View Code

图片:
技术分享

 

双缓冲机制简介

标签:

原文地址:http://www.cnblogs.com/rookiechen/p/5323364.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!