Android编程实现在Bitmap上涂鸦效果

2019-12-10 19:48:55丽君
易采站长站为您分析Android编程实现在Bitmap上涂鸦效果的方法,涉及Android界面布局,事件响应及Bitmap操作的相关技巧,具有一定参考借鉴价值,需要的朋友可以参考下  

本文实例讲述了Android编程实现在Bitmap上涂鸦效果。,具体如下:

布局文件:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent" 
 android:orientation="vertical" > 
 <LinearLayout 
  android:id="@+id/handwriteview" 
  android:layout_width="wrap_content" 
  android:layout_height="wrap_content" /> 
 <LinearLayout 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:orientation="horizontal" 
  android:gravity="center_horizontal" > 
  <Button 
   android:id="@+id/clear" 
   android:layout_width="200dp" 
   android:layout_height="wrap_content" 
   android:text="清屏" /> 
 </LinearLayout> 
</LinearLayout> 

重写的View文件:

public class HandWrite extends View 
{ 
 private Paint paint = null; 
 private Bitmap originalBitmap = null; 
 private Bitmap new1Bitmap = null; 
 private Bitmap new2Bitmap = null; 
 private float clickX = 0,clickY = 0; 
 private float startX = 0,startY = 0; 
 private boolean isMove = true; 
 private boolean isClear = false; 
 private int color = Color.GREEN; 
 private float strokeWidth = 2.0f; 
 public HandWrite(Context context,Bitmap b) 
 { 
  super(context); 
  originalBitmap = Bitmap.createBitmap(b).copy(Bitmap.Config.ARGB_8888, true); 
  new1Bitmap = Bitmap.createBitmap(originalBitmap); 
 } 
 public void clear(){ 
  isClear = true; 
  new2Bitmap = Bitmap.createBitmap(originalBitmap); 
  invalidate(); 
 } 
 public void setstyle(float strokeWidth){ 
  this.strokeWidth = strokeWidth; 
 } 
 @Override 
 protected void onDraw(Canvas canvas) 
 { 
  super.onDraw(canvas); 
  canvas.drawBitmap(HandWriting(new1Bitmap), 0, 0,null); 
 } 
 public Bitmap HandWriting(Bitmap originalBitmap) 
 { 
  Canvas canvas = null; 
  if(isClear){ 
   canvas = new Canvas(new2Bitmap); 
  } 
  else{ 
   canvas = new Canvas(originalBitmap); 
  } 
  paint = new Paint(); 
  paint.setStyle(Style.STROKE); 
  paint.setAntiAlias(true); 
  paint.setColor(color); 
  paint.setStrokeWidth(strokeWidth); 
  if(isMove){ 
   canvas.drawLine(startX, startY, clickX, clickY, paint); 
  } 
  startX = clickX; 
  startY = clickY; 
  if(isClear){ 
   return new2Bitmap; 
  } 
  return originalBitmap; 
 } 
 @Override 
 public boolean onTouchEvent(MotionEvent event) 
 { 
  clickX = event.getX(); 
  clickY = event.getY(); 
  if(event.getAction() == MotionEvent.ACTION_DOWN){ 
   isMove = false; 
   invalidate(); 
   return true; 
  } 
  else if(event.getAction() == MotionEvent.ACTION_MOVE){ 
   isMove = true; 
   invalidate(); 
   return true; 
  } 
  return super.onTouchEvent(event); 
 } 
}