本文實例為大家分享了Android實現畫板的具體代碼,采用的技術是雙緩沖技術,供大家參考,具體內容如下
1.雙緩沖技術的概念
所謂的雙緩沖技術其實很簡單,當程序需要在指定的View上進行繪制時,程序并不需要直接繪制到該View組件,而是先繪制到一個內存中的Bitmap圖片上(就是緩沖),等內存中的Bitmap繪制好之后,再一次性將Bitmap繪制到View組件上。
2.Android采用雙緩沖實現畫板
實現的思路:
1).定義一個內存中圖片,將他作為緩沖區Bitmap cacheBitmap = null;
2).定義緩沖區Cache的Canvas對象 Canvas cacheCanvas = null;
3).設置cacheCanvas將會繪制到內存的bitmap上。
cacheCanvas.setBitmap(cacheBitmap);
4). 將cacheBitmap繪制到該View上.
canvas.drawBitmap(cacheBitmap,0,0,p);
3.代碼實現
package com.lidong.android_ibrary.view;import android.content.Context;import android.graphics.Bitmap;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Path;import android.util.AttributeSet;import android.view.MotionEvent;import android.view.View;/***@類名 : DrawView*@描述 : 使用雙緩存技術實現繪制*@時間 : 2016/4/26 9:18*@作者: 李東*@郵箱 : lidong@chni.com.cn*@company: chni*/public class DrawView extends View { float preX; float preY; private Path path; private Paint paint = null; private int VIEW_WIDTH = 800; private int VIEW_HEIGHT = 600; //定義一個內存中圖片,將他作為緩沖區 Bitmap cacheBitmap = null; //定義緩沖區Cache的Canvas對象 Canvas cacheCanvas = null; public DrawView(Context context) { this(context,null); } public DrawView(Context context, AttributeSet attrs) { super(context, attrs); //創建一個與該VIew相同大小的緩沖區 cacheBitmap = Bitmap.createBitmap(VIEW_WIDTH,VIEW_HEIGHT,Bitmap.Config.ARGB_8888); //創建緩沖區Cache的Canvas對象 cacheCanvas = new Canvas(); path = new Path(); //設置cacheCanvas將會繪制到內存的bitmap上 cacheCanvas.setBitmap(cacheBitmap); paint = new Paint(); paint.setColor(Color.RED); paint.setFlags(Paint.DITHER_FLAG); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(5); paint.setAntiAlias(true); paint.setDither(true); } @Override protected void onDraw(Canvas canvas) { Paint p = new Paint(); //將cacheBitmap繪制到該View canvas.drawBitmap(cacheBitmap,0,0,p); canvas.drawPath(path,paint); } @Override public boolean onTouchEvent(MotionEvent event) { //獲取拖動時間的發生位置 float x = event.getX(); float y = event.getY(); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: path.moveTo(x,y); preX = x; preY = y; break; case MotionEvent.ACTION_MOVE: path.quadTo(preX,preY,x,y); preX = x; preY = y; break; case MotionEvent.ACTION_UP: //這是是調用了cacheBitmap的Canvas在繪制 cacheCanvas.drawPath(path,paint); path.reset(); break; } invalidate();//在UI線程刷新VIew return true; }}4.實現的效果

代碼下載:Android實現畫板代碼
以上就是本文的全部內容,希望對大家學習Android軟件編程有所幫助。
新聞熱點
疑難解答