Adding an Image to a Canvas in Android

泄露秘密 提交于 2019-12-07 12:45:08

问题


Good Day Everyone

I was hoping if you could help me understand the concepts of understanding how to add an image into a canvas on a OnTouchEvent implemented on a View. So far, this is what i've come up with.
parent is the Activity where in this customized view is instantiated and is added into.

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

public void insertImage()
{
    if (parent.selected_icon.contentEquals("image1"))
    {
        image = getResources().getDrawable(R.drawable.image1);
    }
    else if (parent.selected_icon.contentEquals("image1"))
    {
        image = getResources().getDrawable(R.drawable.image2);
    }
    else if (parent.selected_icon.contentEquals("iamge3"))
    {
        image = getResources().getDrawable(R.drawable.image3);
    }

    Rect srcRect = new Rect(0, 0, image.getIntrinsicWidth(), 
            image.getIntrinsicHeight());
    Rect dstRect = new Rect(srcRect);

    Bitmap bitmap = Bitmap.createBitmap(image.getIntrinsicWidth(), 
            image.getIntrinsicHeight(), Bitmap.Config.ALPHA_8);

    Canvas canvas = new Canvas();
    canvas.drawBitmap(bitmap, srcRect, dstRect, null);
    invalidate();
}

回答1:


When you want to draw over a view, you have to do that in onDraw(), using the Canvas passed there. That Canvas is already bound to the Bitmap that is the actual drawing of your view.

I had to do something similar and my approach was like this:

  • I had a list of "things to be drawn over the view" as a member of the class.
  • whenever I added something to that list, I called invalidate(), so that onDraw() would get called.
  • My onDraw() looked like this:

...

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas); // the default drawing

    for(ThingToBeDrawn thing : mListOfThingsToBeDrawn) {
         thing.drawThing(canvas); // draw each thing over the view
    }
}

A Canvas is just a tool used to draw a Bitmap, and it works quite differently than SurfaceView.



来源:https://stackoverflow.com/questions/5823680/adding-an-image-to-a-canvas-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!