Android Bitmap Custom View on High Resolution Screens having poor performance
-
24-06-2021 - |
Question
I am making a custom list view item. Extending View and overriding the onDraw method.
private Bitmap bmpScaledBackground; //with size:(screenWidth , screenHeight/4)
@Override
public void onDraw(Canvas canvas){
canvas.drawBitmap(bmpScaledBackground , 0 , 0 , null);
//...more of that
}
So far it works quite well on normal phones such as Galaxy SII.
However when it comes to Galaxy Nexus, the performance is poor. I believe it is because of the large resolution of GN (1280x720).
In the above case, the background bitmap (bmpScaledBackground) alone is as large as 720x320 which takes a long time to draw. Not to mention the risk of OOM.
I am writing to ask if there is a more scalable way (except SurfaceView and OpenGL) to make a custom view.
Sorry for my poor english.
Solution
My options: 1,Use 'xxx.9.png' format pics resources. 2,Use a compress bitmap.
//get opts
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true ;
Bitmap bitmap = BitmapFactory.decodeFile(imageFile, opts);
//get a appropriate inSampleSize
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8 ) {
roundedSize = 1 ;
while (roundedSize < initialSize) {
roundedSize <<= 1 ;
}
} else {
roundedSize = (initialSize + 7 ) / 8 * 8 ;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == - 1 ) ? 1 :
( int ) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == - 1 ) ? 128 :
( int ) Math.min(Math.floor(w / minSideLength),
Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == - 1 ) &&
(minSideLength == - 1 )) {
return 1 ;
} else if (minSideLength == - 1 ) {
return lowerBound;
} else {
return upperBound;
}
}
//last get a well bitmap.
BitmapFactory.Options opts =new BitmapFactory.Options();
opts.inSampleSize = inSampleSize;// inSampleSize should be index value of 2.
Bitmap wellbmp =null;
wellbmp = BitmapFactory.decodeResource(getResources(), mImageIds[position],opts);
Good luck! ^-^
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow