Android如何将图库图像添加到绘图应用程序中

时间:2013-09-01 15:51:47

标签: android bitmap drawing

我正在创建一个应用程序,人们可以在其中绘制草图并保存到库中。我已经完成并且工作正常。我想要做的是从画廊拍摄一张图片,并能够画上它。我已经能够调出图库来选择图像,但我还没有弄清楚如何将该图像嵌入画布然后绘制

这是我的图库按钮代码:

else if(view.getId()==R.id.GalleryButton){
            //new button
            AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
            newDialog.setTitle("New drawing");
            newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
            newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    Intent choosePictureIntent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(choosePictureIntent, 0);


                }

            });
            newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
                public void onClick(DialogInterface dialog, int which){
                    dialog.cancel();
                }
            });
            newDialog.show();
        }

我确信在startActivityForResult部分之后必须有一些事情,这是我无法解决的问题。我希望嵌入图像的地方是(R.id.drawing)

编辑:

以下是完整的代码:

public class MainActivity extends Activity implements OnClickListener {

//custom drawing view
private DrawingView drawView;
//buttons
private ImageButton currPaint, drawBtn, eraseBtn, newBtn, saveBtn, galleryBtn, cameraBtn;
//sizes
private float smallBrush, mediumBrush, largeBrush;

Bitmap bitmap;

protected static final int CAMERA_PIC_REQUEST = 0;

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

    //get drawing view
    drawView = (DrawingView)findViewById(R.id.drawing);

    //get the palette and first color button
    LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors);
    currPaint = (ImageButton)paintLayout.getChildAt(0);
    currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));

    //sizes from dimensions
    smallBrush = getResources().getInteger(R.integer.small_size);
    mediumBrush = getResources().getInteger(R.integer.medium_size);
    largeBrush = getResources().getInteger(R.integer.large_size);

    //draw button
    drawBtn = (ImageButton)findViewById(R.id.draw_btn);
    drawBtn.setOnClickListener(this);

    //set initial size
    drawView.setBrushSize(mediumBrush);

    //erase button
    eraseBtn = (ImageButton)findViewById(R.id.erase_btn);
    eraseBtn.setOnClickListener(this);

    //new button
    newBtn = (ImageButton)findViewById(R.id.new_btn);
    newBtn.setOnClickListener(this);

    //save button
    saveBtn = (ImageButton)findViewById(R.id.save_btn);
    saveBtn.setOnClickListener(this);

    //new button
    galleryBtn = (ImageButton)findViewById(R.id.GalleryButton);
    galleryBtn.setOnClickListener(this);

    //new button
    cameraBtn = (ImageButton)findViewById(R.id.camera_btn);
    cameraBtn.setOnClickListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

//user clicked paint
public void paintClicked(View view){
    //use chosen color

    //set erase false
    drawView.setErase(false);
    drawView.setBrushSize(drawView.getLastBrushSize());

    if(view!=currPaint){
        ImageButton imgView = (ImageButton)view;
        String color = view.getTag().toString();
        drawView.setColor(color);
        //update ui
        imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed));
        currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint));
        currPaint=(ImageButton)view;
    }
}

@Override
public void onClick(View view){

    if(view.getId()==R.id.draw_btn){
        //draw button clicked
        final Dialog brushDialog = new Dialog(this);
        brushDialog.setTitle("Brush size:");
        brushDialog.setContentView(R.layout.brush_chooser);
        //listen for clicks on size buttons
        ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
        smallBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                drawView.setErase(false);
                drawView.setBrushSize(smallBrush);
                drawView.setLastBrushSize(smallBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
        mediumBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                drawView.setErase(false);
                drawView.setBrushSize(mediumBrush);
                drawView.setLastBrushSize(mediumBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
        largeBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                drawView.setErase(false);
                drawView.setBrushSize(largeBrush);
                drawView.setLastBrushSize(largeBrush);
                brushDialog.dismiss();
            }
        });
        //show and wait for user interaction
        brushDialog.show();
    }
    else if(view.getId()==R.id.erase_btn){
        //switch to erase - choose size
        final Dialog brushDialog = new Dialog(this);
        brushDialog.setTitle("Eraser size:");
        brushDialog.setContentView(R.layout.brush_chooser);
        //size buttons
        ImageButton smallBtn = (ImageButton)brushDialog.findViewById(R.id.small_brush);
        smallBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                drawView.setErase(true);
                drawView.setBrushSize(smallBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton mediumBtn = (ImageButton)brushDialog.findViewById(R.id.medium_brush);
        mediumBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                drawView.setErase(true);
                drawView.setBrushSize(mediumBrush);
                brushDialog.dismiss();
            }
        });
        ImageButton largeBtn = (ImageButton)brushDialog.findViewById(R.id.large_brush);
        largeBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                drawView.setErase(true);
                drawView.setBrushSize(largeBrush);
                brushDialog.dismiss();
            }
        });
        brushDialog.show();
    }
    else if(view.getId()==R.id.new_btn){
        //new button
        AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
        newDialog.setTitle("New drawing");
        newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
        newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                drawView.startNew();
                dialog.dismiss();
            }
        });
        newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                dialog.cancel();
            }
        });
        newDialog.show();
    }
    else if(view.getId()==R.id.save_btn){
        //save drawing
        AlertDialog.Builder saveDialog = new AlertDialog.Builder(this);
        saveDialog.setTitle("Save drawing");
        saveDialog.setMessage("Save drawing to device Gallery?");
        saveDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                //save drawing
                drawView.setDrawingCacheEnabled(true);
                //attempt to save
                String imgSaved = MediaStore.Images.Media.insertImage(
                        getContentResolver(), drawView.getDrawingCache(),
                        UUID.randomUUID().toString()+".png", "drawing");
                //feedback
                if(imgSaved!=null){
                    Toast savedToast = Toast.makeText(getApplicationContext(), 
                            "Drawing saved to Gallery!", Toast.LENGTH_SHORT);
                    savedToast.show();
                }
                else{
                    Toast unsavedToast = Toast.makeText(getApplicationContext(), 
                            "Oops! Image could not be saved.", Toast.LENGTH_SHORT);
                    unsavedToast.show();
                }
                drawView.destroyDrawingCache();
            }
        });
        saveDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                dialog.cancel();
            }
        });
        saveDialog.show();
    }
    else if(view.getId()==R.id.GalleryButton){
        //new button
        AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
        newDialog.setTitle("New drawing");
        newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
        newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                Intent choosePictureIntent = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(choosePictureIntent, 101);


            }

        });
        newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                dialog.cancel();
            }
        });
        newDialog.show();
    }

    else if(view.getId()==R.id.camera_btn){
        //new button
        AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
        newDialog.setTitle("New drawing");
        newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
        newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                Intent intent = new Intent(getApplicationContext(), ChoosePicture.class); 
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                startActivity(intent);


            }

        });
        newDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int which){
                dialog.cancel();
            }
        });
        newDialog.show();
}

@Override
                    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                        InputStream stream = null;
                        if (requestCode == 101&& resultCode == Activity.RESULT_OK)
                        {
                            try 
                            {
                                // We need to recycle unused bitmaps
                                if (bitmap != null) 
                                {
                                    bitmap.recycle();
                                }
                                stream = getContentResolver().openInputStream(data.getData());
                                bitmap = BitmapFactory.decodeStream(stream);
                                ImageView imageView=(ImageView)findViewById(R.id.drawing);
                                imageView.setImageBitmap(bitmap);
                                imageView.getLayoutParams().height = bitmap.getHeight()/8;
                            }
                            catch (FileNotFoundException e)
                            {
                                e.printStackTrace();
                            }
                            if (stream != null)
                            {
                                try
                                {
                                    stream.close();
                                }
                                catch (IOException e)
                                {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                };
}

RAGHUNANDAN的代码:

else if(view.getId()==R.id.GalleryButton){
            //new button
            AlertDialog.Builder newDialog = new AlertDialog.Builder(this);
            newDialog.setTitle("New drawing");
            newDialog.setMessage("Start new drawing (you will lose the current drawing)?");
            newDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
                public void  setDrawingThemefrmGallery()
                {
                    // To open up a gallery browser
                    Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
                    // To handle when an image is selected from the browser, add the following to your Activity
                }

                public void onActivityResult(int requestCode, int resultCode, Intent data) {
                if (resultCode == RESULT_OK) {
                if (requestCode == 1) {
                Uri currImageURI = data.getData();
                String s= getRealPathFromURI(currImageURI);
                File file = new File(s);

                if (file.exists()) {
                Drawable d = Drawable.createFromPath(file.getAbsolutePath());
                drawView.setBackground(d);
                }
                else
                {
                       // file does not exist
                }

                }
                }
                }
                /**
                 * @param contentURI
                 * @return
                 */
                private String getRealPathFromURI(Uri contentURI) {
                    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
                    if (cursor == null) { // Source is Dropbox or other similar local file path
                        return contentURI.getPath();
                    } else { 
                        cursor.moveToFirst(); 
                        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
                        return cursor.getString(idx); 
                    }
                }

非常感谢您的进步。

2 个答案:

答案 0 :(得分:1)

尝试以下内容。

此外,如果图像太大而无法放入,则可能需要缩小才能将其设置为背景。根据需要使用适当的BitmapFactory.decode方法。

public void  setDrawingThemefrmGallery()
{
    // To open up a gallery browser
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select Picture"),1);
    // To handle when an image is selected from the browser, add the following to your Activity
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
Uri currImageURI = data.getData();
String s= getRealPathFromURI(currImageURI);
File file = new File(s);

if (file.exists()) {
Drawable d = Drawable.createFromPath(file.getAbsolutePath());
drawView.setBackground(d);
}
else
{
       // file does not exist
}

}
}
}
/**
 * @param contentURI
 * @return
 */
private String getRealPathFromURI(Uri contentURI) {
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        return contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        return cursor.getString(idx); 
    }
}

快照

从图库中选取的图像是图纸视图的背景,您可以在图纸上绘图。

enter image description here

答案 1 :(得分:0)

startActivityForResult

添加请求代码
startActivityForResult(choosePictureIntent, 101);

然后将此添加到您的代码

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    InputStream stream = null;
    if (requestCode == 101&& resultCode == Activity.RESULT_OK)
    {
        try 
        {
            // We need to recycle unused bitmaps
            if (bitmap != null) 
            {
                bitmap.recycle();
            }
            stream = getContentResolver().openInputStream(data.getData());
            bitmap = BitmapFactory.decodeStream(stream);
            ImageView imageView=(ImageView)findViewById(R.id.drawing);
            imageView.setImageBitmap(bitmap);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        if (stream != null)
        {
            try
            {
                stream.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}

就是这样......用户选择的图片现在位于 R.id.drawing