android之简易画板(涂鸦)实例(透明背景)
16lz
2021-01-23
一、创建变量
//DoodleViewprivate Paint mPaint = new Paint();private List mPathList = new ArrayList<>(); // 保存涂鸦轨迹的集合private float mLastX, mLastY;private Path mCurrentPath; // 当前的涂鸦轨迹private Canvas canvas;private ImageView imageView;private Bitmap bitmap;
二、初始化变量
void initDoodleView(){ imageView = findViewById(R.id.doodleView_container); imageView.setOnTouchListener(this); // 设置画笔 mPaint.setColor(Color.RED); mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(3); mPaint.setAntiAlias(true); mPaint.setStrokeCap(Paint.Cap.ROUND); //创建黑色背景的bitmap //bitmap = Bitmap.createBitmap(imageView.getWidth(),imageView.getHeight(), Bitmap.Config.RGB_565); //获取drawable中的透明图片创建透明背景的bitmap Bitmap bitmapT = BitmapFactory.decodeResource(getResources(),R.drawable.transparent); //把bitmapT从坐标(0,0)开始裁剪成需要的大小 bitmap = Bitmap.createBitmap(bitmapT, 0, 0, imageView.getWidth(), imageView.getHeight()); canvas = new Canvas(bitmap); imageView.setImageBitmap(bitmap);}
三、在onTouch事件中添加涂鸦路径
@Overridepublic boolean onTouch(View view, MotionEvent motionEvent) { int x = (int)motionEvent.getX();//motionEvent.getRawX(); int y = (int)motionEvent.getY(); view.performClick(); switch(motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: mCurrentPath = new Path(); // 新的涂鸦 mPathList.add(mCurrentPath); // 添加的集合中 mCurrentPath.moveTo(motionEvent.getX(), motionEvent.getY()); mLastX = motionEvent.getX(); mLastY = motionEvent.getY(); view.invalidate(); // 刷新 break; case MotionEvent.ACTION_UP: mCurrentPath.quadTo( mLastX, mLastY, (motionEvent.getX() + mLastX) / 2, (motionEvent.getY() + mLastY) / 2); // 使用贝塞尔曲线 让涂鸦轨迹更圆滑 mCurrentPath = null; // 轨迹结束 view.invalidate(); // 刷新 break; case MotionEvent.ACTION_MOVE: mCurrentPath.quadTo( mLastX, mLastY, (motionEvent.getX() + mLastX) / 2, (motionEvent.getY() + mLastY) / 2); // 使用贝塞尔曲线 让涂鸦轨迹更圆滑 mLastX = motionEvent.getX(); mLastY = motionEvent.getY(); canvas.drawPath(mCurrentPath, mPaint); view.invalidate(); // 刷新 break; } return true; }
四、清除Imageview中的所有涂鸦
//bitmap = Bitmap.createBitmap(imageView.getWidth(),imageView.getHeight(), Bitmap.Config.RGB_565);bitmap = Bitmap.createBitmap(bitmapT, 0, 0, imageView.getWidth(),imageView.getHeight());canvas = new Canvas(bitmap);if (bitmap!=null && imageView!=null) imageView.setImageBitmap(bitmap);
更多相关文章
- Android 动画--使用Path来规划动画的轨迹
- java android maven环境变量基本配置
- android makefile 常用宏名称和内置变量
- android 设置activity通用的全局变量(新手必备)
- Android 百度鹰眼轨迹SDK(v2.1.6)