Frage

Ich zeichne 2D -Bilder auf der Leinwand.

Ich möchte das auf Canvas gezeigte Bild speichern, wie ich es tun kann, wie kann ich das tun?

War es hilfreich?

Lösung

  1. Erstellen Sie eine leere Bitmap
  2. Erstellen Sie ein neues Canvas -Objekt und übergeben Sie diese Bitmap daran
  3. Call View.Draw (Canvas) über das Canvas -Objekt übergeben, das Sie gerade erstellt haben. Einzelheiten finden Sie unter Dokumentation der Methode.
  4. Verwenden Sie Bitmap.comPress (), um den Inhalt der Bitmap in einen Ausgabestream zu schreiben.

Pseudocode:

Bitmap  bitmap = Bitmap.createBitmap( view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 

Andere Tipps

  1. Setzen Sie den Zeichnungscache aktiviert
  2. Zeichnen Sie alles, was Sie wollen
  3. Holen Sie sich Bitmap -Objekt aus der Sicht
  4. Komprimieren Sie die Bilddatei und speichern Sie die Bilddatei

import java.io.File;
import java.io.FileOutputStream;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class CanvasTest extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Draw2d d = new Draw2d(this);
        setContentView(d);
    }

    public class Draw2d extends View {

        public Draw2d(Context context) {
            super(context);
            setDrawingCacheEnabled(true);
        }

        @Override
        protected void onDraw(Canvas c) {
            Paint paint = new Paint();
            paint.setColor(Color.RED);          
            c.drawCircle(50, 50, 30, paint);

            try {
                getDrawingCache().compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("/mnt/sdcard/arun.jpg")));
            } catch (Exception e) {
                Log.e("Error--------->", e.toString());
            }
            super.onDraw(c);
        }

    }

}

Leinwand zu JPG:

Canvas canvas = null;
FileOutputStream fos = null;
Bitmap bmpBase = null;

bmpBase = Bitmap.createBitmap(image_width, image_height, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bmpBase);
// draw what ever you want canvas.draw...

// Save Bitmap to File
try
{
    fos = new FileOutputStream(your_path);
    bmpBase.compress(Bitmap.CompressFormat.PNG, 100, fos);

    fos.flush();
    fos.close();
    fos = null;
}
catch (IOException e)
{
    e.printStackTrace();
}
finally
{
    if (fos != null)
    {
        try
        {
            fos.close();
            fos = null;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top