Android中绘图板的实现
生活随笔
收集整理的這篇文章主要介紹了
Android中绘图板的实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看到題目大家就知道這個是要做什么了。其實不光是繪圖板,還有簽名也可以用這個。我們直接上自定義控件。
public class DrawPicture extends View {private Paint mPaint; //繪制線條的Pathprivate Path mPath; //記錄用戶繪制的Pathprivate Canvas mCanvas; //內存中創建的Canvasprivate Bitmap mBitmap; //緩存繪制的內容private int mLastX;private int mLastY;private Context mContext;public DrawPicture(Context context) {super(context);init(context);}public DrawPicture(Context context, AttributeSet attrs) {super(context, attrs);init(context);}public DrawPicture(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);init(context);}private void init(Context context) {mContext = context;mPath = new Path();mPaint = new Paint(); //初始化畫筆mPaint.setColor(Color.GREEN);mPaint.setAntiAlias(true);mPaint.setDither(true);mPaint.setStyle(Paint.Style.STROKE);mPaint.setStrokeJoin(Paint.Join.ROUND); //結合處為圓角mPaint.setStrokeCap(Paint.Cap.ROUND); // 設置轉彎處為圓角mPaint.setStrokeWidth(20); // 設置畫筆寬度}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int width = getMeasuredWidth();int height = getMeasuredHeight();// 初始化bitmap,CanvasmBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);mCanvas = new Canvas(mBitmap);}//重寫該方法,在這里繪圖@Overrideprotected void onDraw(Canvas canvas) {drawPath();canvas.drawBitmap(mBitmap, 0, 0, null);}//繪制線條private void drawPath() {mCanvas.drawPath(mPath, mPaint);}@Overridepublic boolean onTouchEvent(MotionEvent event) {int action = event.getAction();int x = (int) event.getX();int y = (int) event.getY();switch (action) {case MotionEvent.ACTION_DOWN:mLastX = x;mLastY = y;mPath.moveTo(mLastX, mLastY);break;case MotionEvent.ACTION_MOVE:int dx = Math.abs(x - mLastX);int dy = Math.abs(y - mLastY);if (dx > 3 || dy > 3)mPath.lineTo(x, y);mLastX = x;mLastY = y;break;}invalidate();return true;}public void savePic() {// 保存繪圖為本地圖片try {mCanvas.save();mCanvas.restore();List<String> list = new ArrayList<>();list.add("pics");File file = new File(PathGetUtil.getLongwayPath(mContext,list),"pic"+System.currentTimeMillis()+".jpg");// 保存到sdcard根目錄下,文件名為share_pic.pngFile fileDir = new File(PathGetUtil.getLongwayPath(mContext,list));if (!fileDir.exists()){fileDir.mkdirs();}if (!file.exists()){file.createNewFile();}FileOutputStream fos = null;fos = new FileOutputStream(file);mBitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);fos.close();} catch (IOException e) {e.printStackTrace();}} }保存的方法中涉及一段PathGerUtil.getLongwayPath方法的調用,這個就是組裝保存路徑的一個方法,大家可以自己寫或者用自己的工具。
總結
以上是生活随笔為你收集整理的Android中绘图板的实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python:比较人脸识别中galler
- 下一篇: android sina oauth2.