手绘画布并保存图片,涉及canvas画布大小问题

手绘画布并保存图片,涉及canvas画布大小问题_第1张图片
TIM截图20170717105518.png

在屏幕内画画,但是只覆盖了屏幕的一部分,原因是定义了画布的大小为480*800,并且定义画布大小没有在onDraw()方法中,因为画是一个重复的过程,鼠标抬起再按下也重新进这个方法,会new一个新的画布出来,原来画的东西就没啦。

/**
 * Created by HASEE on 2017/7/17 10:24
 * 手绘
 */

public class HandDrawView extends View {
    private Paint paint;
    private Canvas cacheCanvas;
    private Bitmap cachebBitmap;
    private Path path;

    private int clr_bg, clr_fg;

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

    public HandDrawView(Context context, AttributeSet attrs) {
        super(context, attrs);

        clr_bg = Color.WHITE;
        clr_fg = Color.CYAN;

        paint = new Paint();
        paint.setAntiAlias(true); // 抗锯齿  
        paint.setStrokeWidth(3); // 线条宽度  
        paint.setStyle(Paint.Style.STROKE); // 画轮廓  
        paint.setColor(clr_fg); // 颜色  

        path = new Path();
        // 创建一张屏幕大小的位图,作为缓冲  
        cachebBitmap = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
        cacheCanvas = new Canvas(cachebBitmap);
        cacheCanvas.drawColor(clr_bg);
    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(clr_bg);

        /*不能放在这里,因为画是一个重复的过程,鼠标抬起再按下也重新进这个方法,
        会new一个新的画布出来,原来画的东西就没啦*/
//        cachebBitmap = Bitmap.createBitmap(480, 800, Bitmap.Config.ARGB_8888);
//        cacheCanvas = new Canvas(cachebBitmap);
//        cacheCanvas.drawColor(clr_bg);

        // 绘制上一次的,否则不连贯  
        canvas.drawBitmap(cachebBitmap, 0, 0, null);
        canvas.drawPath(path, paint);
    }

    /**
     * 清空画布
     */
    public void clear() {
        path.reset();
        cacheCanvas.drawColor(clr_bg);
        invalidate();
    }

    /**
     * 将画布的内容保存到文件
     *
     * @param filename
     * @throws FileNotFoundException
     */
    public void saveToFile(String filename) throws FileNotFoundException {
        File f = new File(filename);
        if (f.exists())
            throw new RuntimeException("文件:" + filename + " 已存在!");

        FileOutputStream fos = new FileOutputStream(new File(filename));
        //将 bitmap 压缩成其他格式的图片数据  
        cachebBitmap.compress(Bitmap.CompressFormat.PNG, 50, fos);
        try {
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
    }

    private float cur_x, cur_y;
    private boolean isMoving;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub  
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                cur_x = x;
                cur_y = y;
                path.moveTo(cur_x, cur_y);
                isMoving = true;
                break;
            }

            case MotionEvent.ACTION_MOVE: {
                if (!isMoving)
                    break;

                // 二次曲线方式绘制  
                path.quadTo(cur_x, cur_y, x, y);
                // 下面这个方法貌似跟上面一样  
                // path.lineTo(x, y);  
                cur_x = x;
                cur_y = y;
                break;
            }

            case MotionEvent.ACTION_UP: {
                // 鼠标弹起保存最后状态  
                cacheCanvas.drawPath(path, paint);
                path.reset();
                isMoving = false;
                break;
            }
        }

        // 通知刷新界面  
        invalidate();

        return true;
    }
}
public class ShouhuiActivity extends AppCompatActivity implements View.OnClickListener {

    private HandDrawView handDrawView;
    private Button clear, save;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shouhui);

        handDrawView = (HandDrawView) findViewById(R.id.handView);
        clear = (Button) findViewById(R.id.iv_btn_clear);
        save = (Button) findViewById(R.id.iv_btn_save);
        clear.setOnClickListener(this);
        save.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_btn_clear:
                handDrawView.clear();
                break;

            case R.id.iv_btn_save: {
                try {
                    String sdState = Environment.getExternalStorageState(); // 判断sd卡是否存在
                    // 检查SD卡是否可用
                    if (!sdState.equals(android.os.Environment.MEDIA_MOUNTED)) {
                        Toast.makeText(this, "SD卡未准备好!", Toast.LENGTH_SHORT).show();
                        break;
                    }
                    //获取系统图片存储路径
                    File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
                    // Make sure the Pictures directory exists.
                    path.mkdirs();
                    //根据当前时间生成图片名称
                    Calendar c = Calendar.getInstance();
                    String name = ""
                            + c.get(Calendar.YEAR) + c.get(Calendar.MONTH) + c.get(Calendar.DAY_OF_MONTH)
                            + c.get(Calendar.HOUR_OF_DAY) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND)
                            + ".png";
                    //合成完整路径,注意 / 分隔符
                    String string = path.getPath() + "/" + name;
                    handDrawView.saveToFile(string);
                    Toast.makeText(this, "保存成功!\n文件保存在:" + string, Toast.LENGTH_LONG).show();
                } catch (FileNotFoundException e) {
                    Toast.makeText(this, "保存失败!\n" + e, Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }
}

你可能感兴趣的:(手绘画布并保存图片,涉及canvas画布大小问题)