开发者

How to add 3 images in a canvas in android

I have 3 images that I want to add one after other on a canvas. This is my code:-

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageButton im1 = (ImageButton)findViewById(R.id.btnPN); 
    im1.setBackgroundDrawable(getImage());       
}

public BitmapDrawable getImage()
{

    Drawable image1 = getResources().getDrawable(R.drawable.imagename);
    Drawable image2 = getResources().getDrawable(R.drawable.imagename);
    Drawable image3 = getResources().getDrawable(R.drawable.imagename);

    Bitmap bitmap = Bitmap.createBitmap(image1.getIntrinsicWidth()            
          +image2.getIntrinsicWidth()+image3.getIntrinsicWidth(),
          image1.getIntrinsicHeight(),Bitmap.Config.ALPHA_8);

    Canvas canvas = new Canvas(bitmap);

    image1.setBounds(0, 0, image1.getIntrinsicWidth(), image1.getIntrinsicHeight());
    image1.draw(canvas);

    image2.setBounds(image1.getIntrinsicWidth(), 0, image2.getIntrinsicWidth(),
            image2.getIntrinsicHeight());
    image2.draw(canvas);

    image3.setBounds(image1.getIntrinsicWidth()+image2.getIntrinsicWidth(),
                      0, image3.getIntrinsicWidth(),
                      image3.getIntrinsicHeight());
    image3.draw(canvas);


    BitmapDrawable bu = new BitmapDrawable(bitmap);
    return bu;    

}

bu开发者_StackOverflow中文版t this is not working.

Can someone please tell me what I am doing wrong here.

Thanks, Farha


I had to solve something similar not too long ago, and you're nearly there with your solution. However, you should be using Rect objects to offset where you draw your bitmap each time. Assuming you've copied all your images into an array of Bitmaps images[], and you've created your bitmap and canvas as you did above, use the following:

Rect srcRect;
Rect dstRect;

for (int i = 0; i < images.length; i++){
    srcRect = new Rect(0, 0, images[i].getWidth(), images[i].getHeight());
    dstRect = new Rect(srcRect);
    if (i != 0){
        dstRect.offset(images[i-1].getWidht(), 0)
    }
    canvas.drawBitmap(images[i], srcRect, dstRect, null);
}

This will copy them all into one line. It's not too difficult to adapt this to copy 4 images into a square, or something similar, using two for loops.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜