在Android上将画布保存到位图

5 java android bitmapfactory android-canvas

关于将Canvas的内容放入Bitmap,我遇到了一些困难.当我尝试这样做时,文件的文件大小约为5.80KB但看起来完全是空的(每个像素都是'#000').

画布绘制了一系列由手写形成的相互连接的线条.下面是我对视图的onDraw.(我知道它阻止了UI线程/不良做法等等,但是我只需要让它工作)

谢谢.

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

        if (IsTouchDown) {

            // Calculate the points
            Path currentPath = new Path();
            boolean IsFirst = true;
            for(Point point : currentPoints){
                if(IsFirst){
                    IsFirst = false;
                        currentPath.moveTo(point.x, point.y);
                    } else {
                        currentPath.lineTo(point.x, point.y);
                    }
                }

            // Draw the path of points
            canvas.drawPath(currentPath, pen);

            // Attempt to make the bitmap and write it to a file.
            Bitmap toDisk = null;
            try {

                // TODO: Get the size of the canvas, replace the 640, 480
                toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
                canvas.setBitmap(toDisk);
                toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));

            } catch (Exception ex) {


            }

        } else {

            // Clear the points
            currentPoints.clear();

        }
    }
Run Code Online (Sandbox Code Playgroud)

cha*_*nin 12

我有类似的问题,我有解决方案.这里完整的任务代码/不要忘记android.permission.WRITE_EXTERNAL_STORAGE清单中的权限/

  public Bitmap saveSignature(){

      Bitmap  bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      this.draw(canvas); 

      File file = new File(Environment.getExternalStorageDirectory() + "/sign.png");

      try {
           bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
      } catch (Exception e) {
           e.printStackTrace();
      }

      return bitmap;
  }
Run Code Online (Sandbox Code Playgroud)

  • 变得空白 png (2认同)

pra*_*eep 0

或许

canvas.setBitmap(toDisk);
Run Code Online (Sandbox Code Playgroud)

不在正确的位置。

尝试这个 :

toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);              
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));

canvas.setBitmap(toDisk);
Run Code Online (Sandbox Code Playgroud)