自定义View——画板

今天实现的是画板效果

自定义View——画板_第1张图片
image

实现原理

自定义View——画板_第2张图片
image

★根据触摸事件返回的坐标点绘制path路径

 @Override
public boolean onTouchEvent(MotionEvent event) {
    x = event.getX();
    y = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            //当触摸屏幕的时候将点移动到触摸的位置
            path.moveTo(x, y);
            break;
        case MotionEvent.ACTION_MOVE:
            //当滑动的时候将滑动路径连接起来
            path.lineTo(x, y);
            //在滑动的过程中不断更新界面
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            //当手抬起的时候更新界面
            invalidate();
            break;
    }
    return true;
}

★canvas绘制路径

//绘制白色背景
canvas.drawColor(Color.WHITE);
//绘制路径
canvas.drawPath(path, paint);

最后保存自己绘制的图像

 public void save() {
    setDrawingCacheEnabled(false);
    setDrawingCacheEnabled(true);
    new Thread(new Runnable() {
        @Override
        public void run() {
            Bitmap drawingCache = getDrawingCache(true);
            File file = new File(getContext().getCacheDir() +  "123.png");
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(file);
                drawingCache.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                fileOutputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                        try {
                            MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
                                    file.getAbsolutePath(), "sad.png", null);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        // 最后通知图库更新
                        getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
                        Log.e("测试", "保存成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

完整代码

package com.yuyigufen.customview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

/**
 * Created by Administrator on 2018/6/11 0011.
 */

public class MyPaintView extends View {

private float x;
private float y;
private Path path;
private Paint paint;
private Random random;

public MyPaintView(Context context) {
    super(context);
}

public MyPaintView(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init();
}

private void init() {
    random = new Random();
    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setStyle(Paint.Style.STROKE);
    paint.setStrokeWidth(10);
    paint.setColor(Color.RED);
    path = new Path();
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(measureSize(widthMeasureSpec), measureSize(heightMeasureSpec));
}

private int measureSize(int size) {
    int mode = MeasureSpec.getMode(size);
    int s = MeasureSpec.getSize(size);
    if (mode == MeasureSpec.EXACTLY) {
        return s;
    } else if (mode == MeasureSpec.AT_MOST) {
        return Math.min(s, 200);
    } else {
        return 200;
    }
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawColor(Color.WHITE);
    canvas.drawPath(path, paint);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    x = event.getX();
    y = event.getY();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            path.moveTo(x, y);
            break;
        case MotionEvent.ACTION_MOVE:
            path.lineTo(x, y);
            invalidate();
            break;
        case MotionEvent.ACTION_UP:
            invalidate();
            break;
    }
    return true;
}

public void clear() {
    path.reset();
    invalidate();
}

public void save() {
    setDrawingCacheEnabled(false);
    setDrawingCacheEnabled(true);
    new Thread(new Runnable() {
        @Override
        public void run() {
            Bitmap drawingCache = getDrawingCache(true);
            File file = new File(getContext().getCacheDir() +  "123.png");
            FileOutputStream fileOutputStream = null;
            try {
                fileOutputStream = new FileOutputStream(file);
                drawingCache.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
                fileOutputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                        try {
                            MediaStore.Images.Media.insertImage(getContext().getContentResolver(),
                                    file.getAbsolutePath(), "sad.png", null);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        // 最后通知图库更新
                        getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getPath())));
                        Log.e("测试", "保存成功");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}
}

个人博客https://myml666.github.io

你可能感兴趣的:(自定义View——画板)