2013-11-25 2 views
0
##MyDraw.java## 

This part of the code is where the bitmap image is created, the bitmap sits on the canvas, form this point I want to be able to save the image that is created on the bitmap, I have a drop down menu in the MainActivity with a 'save' option.Растровые изображения сберегательные

package com.example.save_file; 

import java.util.Random; 
import android.content.Context; 
import android.graphics.Bitmap; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.RectF; 
import android.view.View; 
import android.view.MotionEvent; 

public class MyDraw extends View 

{ 

Canvas c; 
Bitmap bmp; 
Paint paint; 
Random g; 
float X, Y; 

public MyDraw (Context context) 

{ 

     super(context); 

     g = new Random();   
     Bitmap.Config conf = Bitmap.Config.ARGB_8888; 
     bmp = Bitmap.createBitmap (1100, 1800, conf);    

     paint = new Paint(); 
     paint.setStyle (Paint.Style.STROKE); 
     paint.setColor (Color.WHITE);   

     this.setOnTouchListener (new OnTouchListener() 
     { 
      public boolean onTouch (View v, MotionEvent event) 

      { 

       int h, w, R, G, B, A; 
       float x, y; 

       c = new Canvas (bmp);      

       x = event.getX(); 
       y = event.getY(); 
       System.out.printf ("%f %f\n", X, Y);      

       paint.setAntiAlias (true); 

       w = g.nextInt (70)+90; 
       h = g.nextInt (70); 

       R = g.nextInt (255); 
       G = g.nextInt (255); 
       B = g.nextInt (255); 
       A = g.nextInt (255); 

       paint.setStyle (Paint.Style.FILL); 
       paint.setColor ((A << 24) + (R << 16) + (G << 8) + (B << 0)); 

       if (MyApp.fill == 0) // FILLED SHAPE 
       { 
        paint.setStyle (Paint.Style.FILL); 
        paint.setColor ((A << 24) + (R << 16) + (G << 8) + (B << 0)); 

        if (MyApp.shape == 0) 
          c.drawRect (x, y, x + w, y + h, paint); 
        else 
          c.drawOval(new RectF (x, y, x + w, y + h), paint); 

        paint.setStyle (Paint.Style.STROKE); 
        paint.setColor (Color.BLACK);          

        if (MyApp.shape == 0) 
          c.drawRect (x, y, x + w, y + h, paint); 
       else 
          c.drawOval(new RectF (x, y, x + w, y + h), paint); 
       } 
       else // OUTLINED SHAPE 
       { 
        paint.setStyle (Paint.Style.STROKE); 
        paint.setColor ((A << 24) + (R << 16) + (G << 8) + (B << 0));    
        if (MyApp.shape == 0) 
          c.drawRect (x, y, x + w, y + h, paint); 
        else 
          c.drawOval(new RectF (x, y, x + w, y + h), paint); 
       }         
       paint.setColor (Color.WHITE); 
       invalidate();     
       return true; 

      } 


      }); 

    } 
    @Override 
    protected void onDraw (Canvas c) 
    {   
     super.onDraw (c); 
     c.drawBitmap (bmp, 0, 0, paint); 
    } 
} 

##MyApp.java## 

    package com.example.save_file; 

public class MyApp 

{ 

static public int shape = 0; 
static public int fill = 0; 

} 


##MainActivity.java## 

This is the part of the code where the menu code is, I want to be able to pres the save button here and for the bitmap image to be saved to the phone, preferably a standard gallery folder.

package com.example.save_file; 

import java.io.File; 
import java.io.FileOutputStream; 
import java.util.Random; 

import android.os.Bundle; 
import android.os.Environment; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.os.Bundle; 
import android.app.Activity; 
import android.graphics.Bitmap; 
import android.graphics.Bitmap.CompressFormat; 
import android.view.Menu; 
//import android.gesture.GestureOverlayView; 

public class MainActivity extends Activity { 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     MyDraw d = new MyDraw (this); 
     setContentView (d); 
    }  

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) 
    { 
      super.onCreateOptionsMenu (menu); 
      MenuItem menu1 = menu.add(0, 0, Menu.NONE, "Filled Shape"); 
      MenuItem menu2 = menu.add(0, 1, Menu.NONE, "Outline Shape"); 
      MenuItem menu3 = menu.add(0, 2, Menu.NONE, "Rectangle"); 
      MenuItem menu4 = menu.add(0, 3, Menu.NONE, "Oval"); 
      MenuItem menu5 = menu.add(0, 4, Menu.NONE, "Save!"); 

      return true; 
    } 
    public boolean onOptionsItemSelected(MenuItem item) 
    { 
      switch (item.getItemId()) 

      { 
      case 0: 
       MyApp.fill = 0; 
       return true; 
      case 1: 
       MyApp.fill = 1; 
       return true; 
      case 2: 
       MyApp.shape = 0; 
       return true; 
      case 3: 
       MyApp.shape = 1; 
       return true; 
      default: 
       return super.onOptionsItemSelected(item); 

      case 4: 

       bmp.setDrawingCacheEnabled(true); 
       Bitmap bitmap = bmp.getDrawingCache(); 
       File root = Environment.getExternalStorageDirectory(); 
       File file = new 
        File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg"); 
       try 
       { 
        file.createNewFile(); 
        FileOutputStream ostream = new FileOutputStream(file); 
        bitmap.compress(CompressFormat.JPEG, 100, ostream); 
        ostream.close(); 
       } 
       catch (Exception e) 
       { 
        e.printStackTrace(); 
       } 
        } 
    } 

}

+0

Спасибо, я думаю, что от того, что вы прокомментировали это добавило , –

ответ

0

Я использую этот код, чтобы сохранить любой графический выводимым с помощью холста, как fingerpaint или подобное, я надеюсь, что может быть полезно для вашего case

Задайте экземпляр как глобальный

MyDraw d; 
@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    d = new MyDraw (this); 
    setContentView (d); 
} 

И положите это в случае вашего onOptionsItemSelected();

case 4: 
    try { 
     Bitmap bitmap = Bitmap.createBitmap(d.getWidth(),d.getHeight(), Bitmap.Config.ARGB_8888); 
     Canvas canvas = new Canvas(bitmap); 
     d.draw(canvas); 
     File folder = new File(Environment.getExternalStorageDirectory()+ "/DCIM/Camera/"); 
     if (!folder.exists()) 
      folder.mkdirs(); 
     String fileName = Environment.getExternalStorageDirectory()+ "/DCIM/Camera/img.jpg""; 
     if (new File(fileName).exists()) 
      new File(fileName).delete(); 
     OutputStream stream = new FileOutputStream(fileName); 
     /* 
     * Write bitmap to file using JPEG or PNG and 100% quality hint 
     * for JPEG. 
     */ 
     bitmap.compress(CompressFormat.JPEG, 100, stream); 
     stream.close(); 
     } catch (Exception e) { 
       // TODO Auto-generated catch block 
       Toast.makeText(this, "Error: " + e.getMessage(),Toast.LENGTH_LONG).show(); 
     } 
     break; 

UPDATE: Проверьте, что эмулировать устройство имеет SD Card enter image description here

Напомните, что вы должны добавить разрешения проявить

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
+0

Нет, находится в MainActivity, весь код, который я вам даю, отсутствует в myDraw.java –

+0

Я сделал все это, но у меня есть только эмулятор и HTC, у которого нет SD-карты, У вас есть работа над эмулятором? На данный момент после выбора кнопки сохранения появляется сообщение об ошибке: Ошибка:/storage/emulated/0/DCIM/Camera/img: open failed: EACCES (Permission denied) Спасибо за вашу помощь. –

+0

heck the Update –

Смежные вопросы