1

我正在创建一个应用程序,人们可以在其中绘制草图并保存到画廊。这我已经完成并且工作正常。我想做的是从图库中获取图像并能够在其上进行绘制。我已经能够调出图库来选择图像,但我无法弄清楚如何将该图像嵌入到画布上然后在上面绘图

这是我的画廊按钮代码:

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); 
                    }
                }

非常感谢您。

4

2 回答 2

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); 
    }
}

快照

从图库中挑选的图像,它是您绘图视图的背景,您可以在其上绘图。

在此处输入图像描述

于 2013-09-01T16:16:11.950 回答
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里面

于 2013-09-01T15:58:25.037 回答