本文实例为大家分享了Android画画板展示的具体代码,供大家参考,具体内容如下
main.xml布局
main布局
/* 画板canvas 画板paint 手势识别器 整体思路:因为我是图片是作画,实际是对图片进行修改,起到画图的效果 1.原图,白纸,画笔,画板 2.根据手势识别进行作画 */ public class MainActivity extends AppCompatActivity { private Bitmap bitmap; private Canvas canvas; private ImageView iv; private int startx; private int starty; private Paint paint; private Bitmap bmSrc; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //加载原图 bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.bg); //创建白纸,宽,高,图片的参数 bitmap = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig()); //创建画板,参数是白纸对象 canvas = new Canvas(bitmap); //创建画笔 paint = new Paint(); //在纸上作画 iv=(ImageView)findViewById(R.id.iv); canvas.drawBitmap(bmSrc,new Matrix(), paint); //-----------------手势识别器和画笔结合的知识------------------- //给控件设置手势适配器,可以得到用户在这个控件上所做的手势 iv.setOnTouchListener(new View.OnTouchListener() { //当用户手在这个控件时,指的就是用户的手对控件滑动,按下,松开的三种场景,自动回调 @Override public boolean onTouch(View view, MotionEvent motionEvent) { switch (motionEvent.getAction()){ case MotionEvent.ACTION_DOWN://按下时回调一次 //获取用户手指按下时的坐标 startx = (int) motionEvent.getX(); starty = (int) motionEvent.getY(); break; case MotionEvent.ACTION_MOVE://手指滑动时,不停地调用 int newx = (int) motionEvent.getX(); int newy = (int) motionEvent.getY(); //在背景图画线 canvas.drawLine(startx,starty,newx,newy, paint); startx=newx; starty=newy; iv.setImageBitmap(bitmap); break; case MotionEvent.ACTION_UP://松开时回调一次 break; } //事情分发机制 //true:iv处理该触摸事件 //false:iv不处理该触摸事件,事件传递给上一级 return true; } }); } public void onplay(View view){ switch (view.getId()){ case R.id.red: paint.setColor(Color.RED); break; case R.id.green: paint.setColor(Color.GREEN); break; case R.id.root: paint.setStrokeWidth(5); break; case R.id.save: if(SaveViewUtil.saveScreen(iv)){ Toast.makeText(this, "截图成功", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "截图失败,请检查sdcard是否可用", Toast.LENGTH_SHORT).show(); } break; //涂漆 case R.id.finish: canvas.drawRect(new Rect(0,0,width,height), paint); break; } } }
这是一个把画的图存储SD卡的工具类
public class SaveViewUtil { private static final File rootDir = new File(Environment.getExternalStorageDirectory()+File.separator); /**保存截图的方法*/ public static boolean saveScreen(View view){ //判断sdcard是否可用 if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){ return false; } if(!rootDir.exists()){ rootDir.mkdir(); } view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bitmap = view.getDrawingCache(); try { bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(new File(rootDir,System.currentTimeMillis()+".jpg"))); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; }finally{ view.setDrawingCacheEnabled(false); bitmap = null; } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。