如何通过按钮OnClick保存Canvas图像?

时间:2019-06-26 11:53:58

标签: java android canvas bitmap

我正在尝试使用“保存到图库”选项创建Paint应用程序。我不知道为什么我的OnClick方法不起作用。当我键入:

fos = new FileOutputStream(getFileName());

用红色下划线标记,我不知道为什么。绘画视图在相对布局中设置。我搜索了整个互联网,但没有找到解决此问题的方法。

public class MainActivity extends AppCompatActivity {

    Button save;

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

        save = findViewById(R.id.save);

        final RelativeLayout canva = (RelativeLayout) findViewById(R.id.r1);
        MyDrawView myDrawView = new MyDrawView(this);
        canva.addView(myDrawView);

        save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                canva.setDrawingCacheEnabled(true);
                Bitmap b = canva.getDrawingCache();

                FileOutputStream fos = null;
                try {
                    fos = new FileOutputStream(getFileName()); /// it's underlined in red ERROR
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                b.compress(Bitmap.CompressFormat.PNG, 95, fos);
            }
        });

    }
}
public class MyDrawView extends View {

    private Bitmap mBitmap;
    private Canvas mCanvas;
    private Path mPath;
    private Paint mBitmapPaint;
    private Paint   mPaint;

    public MyDrawView(Context c) {
        super(c);

        mPath = new Path();
        mBitmapPaint = new Paint(Paint.DITHER_FLAG);

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(0xFF000000);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeJoin(Paint.Join.ROUND);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
        mPaint.setStrokeWidth(3);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        mCanvas = new Canvas(mBitmap);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

        canvas.drawPath(mPath, mPaint);
    }

    private float mX, mY;
    private static final float TOUCH_TOLERANCE = 4;

    private void touch_start(float x, float y) {
        mPath.reset();
        mPath.moveTo(x, y);
        mX = x;
        mY = y;
    }
    private void touch_move(float x, float y) {
        float dx = Math.abs(x - mX);
        float dy = Math.abs(y - mY);
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
            mX = x;
            mY = y;
        }
    }
    private void touch_up() {
        mPath.lineTo(mX, mY);
        // commit the path to our offscreen
        mCanvas.drawPath(mPath, mPaint);
        // kill this so we don't double draw
        mPath.reset();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touch_start(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_MOVE:
                touch_move(x, y);
                invalidate();
                break;
            case MotionEvent.ACTION_UP:
                touch_up();
                invalidate();
                break;
        }
        return true;
    }

    public void clear(){
        mBitmap.eraseColor(Color.TRANSPARENT);
        invalidate();
        System.gc();
    }}

3 个答案:

答案 0 :(得分:0)

getFileName()不是MainActivity知道的方法。 如果确实存在,则可能超出MainActivity的范围。

答案 1 :(得分:0)

您需要创建函数 getFileName

File getFileName(){
 String rootPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/MyFolder/";
        File root = new File(rootPath);
        if (!root.exists()) {
            root.mkdirs();
        }
        File f = new File(rootPath + "IMG_"+System.currentTimeMillis()+".png");
        if (f.exists()) {
            f.delete();
        }
        f.createNewFile();

return f;

}

答案 2 :(得分:0)

检查您的getFileName()方法是否通过字符串。您也可以按照以下说明进行操作。

 File file =  new 
 File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "MY_IMAGE.PNG");

 FileOutputStream out = new FileOutputStream(file);
 b.compress(Bitmap.CompressFormat.PNG, 95, out);
            out.flush();
            out.close();
MediaScannerConnection.scanFile(mContext, new String[] { file.toString() }, null,new MediaScannerConnection.OnScanCompletedListener() {
            public void onScanCompleted(String path, Uri uri) {
                Log.i("ExternalStorage", "Scanned " + path + ":");
                Log.i("ExternalStorage", "-> uri=" + uri);
            }
       });

您的图像将以 MY_IMAGE.PNG

的名称保存到外部存储器的“图片”目录中。