开发者

Android: How to: create a new copy of an existing Bitmap?

开发者 https://www.devze.com 2023-04-03 22:24 出处:网络
I will create a simple floor map guide. I have different FLOORS and the corresponding MAPS. FLOORS are buttons and MAPS are png files stored in the sdcard. When I click 1F and corresponding 1Fmap will

I will create a simple floor map guide. I have different FLOORS and the corresponding MAPS. FLOORS are buttons and MAPS are png files stored in the sdcard. When I click 1F and corresponding 1Fmap will be displayed and so with other floors.

I am thinking of the following:

  1. one image view to show the selected map.
  2. Hashmap ( OR ) to handle the bitmaps. use to obtain the bitmap based on the selected floor. then set to ImageView via setImageBitmap(..)
  3. the bitmap to be assigned in the Hashmap are downloaded upon clicking of the floor button. then create the bitmap, set to imageview and the later on store to hashmap upon clicking the other floors.

Here are my technical/design problems:

  1. how to create a copy of bitmap?
  2. is it ok to store it to hashmap gradually or obtain it from the sdcard everytime the floor buttons are click?
  3. if i will be using hashmap, is it ok to use Integer (floor numbers) or String (floornames) as map k开发者_JAVA百科ey?

UPDATE: additional, I am targeting maximum of 20 floors (it means 20 512x512 png files...i am thinking also to adjust it to 256x256 as others suggested).


This answer helped me:

https://stackoverflow.com/a/17068594/1373248

The code is the following:

Bitmap bmp1 = BitmapFactory.decodeResource(cont.getResources(), R.drawable.image);
//then create a copy of bitmap bmp1 into bmp2
Bitmap bmp2 = bmp1.copy(bmp1.getConfig(), true);


Depending on situation you can use:

Bitmap src = ...;
Bitmap dst = src.copy(src.getConfig(), src.isMutable);

The code below creates a copy. That means it copies the pixels from source bitmap and makes completely new Bitmap object. The reason why I am pointing it out because on internet you can find many examples where they use Bitmap.createBitmap() which does not guarantee if the new bitmap will be an object or a reference to older one. And depending on situation you can have problematic behaviour.


Bitmap OLDBitmap = getBitmap();
Bitmap newBmp = Bitmap.createBitmap(OLDBitmap);


public static Bitmap cloneBitmap(Bitmap bitmap) {
    return bitmap.copy(bitmap.getConfig(),bitmap.isMutable());
}


Kotlin extension:

fun Bitmap.copy(): Bitmap? = copy(config, isMutable)


you will get the copy of bitmap as bitmap2

Bitmap bitmap2= bitmap1.copy(bitmap1.getConfig(), true);


  1. To create copy of bitmap you can use:

    Bitmap newBmp = Bitmap.createScaledBitmap(src, dstWidth, dstHeight, filter);

  2. You can gradually get the Image from SD card. NO problem with this implementation.

  3. If you are using Hashmap then you can user the image URL as the Key for Hashmap.

0

精彩评论

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