I try to load the bitmap to a custom SurfaceView in my first image editor application. It will try to scale the image (up or down) to fit with the screen height (yeah, I know it is stupid function, but I am learning android as well). This is the code in the activity
private RelativeLayout topLayout;
private CustomeSurfaceView customeSurfaceView;
public void onCreate(Bundle onSaveBundle) {
// initialize all the views
......
// Scale image to screen
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
if (path != null && bmp == null) {
bmp = AppUtils.loadBitmapFromPath(this, path);
}
Log.d(TAG, "Before scaled: " + bmp.getWidth() + " " + bmp.getHeight());
int scaleHeight = screenHeight;
int scaleWidth = (int) (((float) screenHeight / bmp.getHeight() * 1.0) * bmp.getWidth());
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bmp, scaleWidth, scaleHeight, false);
if (scaledBitmap != bmp) {
bmp.recycle();
}
Log.d(TAG, "After scaled: " + scaledBitmap.getWidth() + " " + scaledBitmap.getHeight());
// Create the work space and load the bitmap
customSurfaceView = new CustomeSurfaceView(this, scaledBitmap);
topLayout.addView(customSurfaceView);
}
And this is the code of the SurfaceView
public class CustomeSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
private Bitmap mainImage;
int maxX;
int maxY;
private int scrollByX;
private int scrollByY;
private int maxLeft;
private int maxRight;
private int maxTop;
private int maxBottom;
private float downX, downY;
private int totalX, totalY;
private float currentXPos;
private float currentYPos;
private int screenHeight;
private int screenWidth;
public CustomeSurfaceView(Context context, Bitmap bitmap) {
super(context);
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
screenWidth = size.x;
screenHeight = size.y;
// set maximum scroll amount (based on center of image)
maxX = (mainImage.getWidth() / 2) - (screenWidth / 2);
maxY = (mainImage.getHeight() / 2) - (screenHeight / 2);
// set scroll limits
maxLeft = (maxX * -1);
maxRight = maxX;
maxTop = (maxY * -1);
maxBottom = maxY;
this.mainImage = bitmap;
setWillNotDraw(false);
getHolder().addCallback(this);
.....
}
/**
*
* @param canvas
*/
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(mainImage, maxLeft, 0, null);
}
}
If I try to scale up, say from 1280 * 800 to 2048 * 1280, then SurfaceView happily load my scaled bitmap
However, if I try to scale down from 3264 * 1840 to 2270 * 1280, I end up with a black screen
My questions are :
- What did I do wrong here?
- If this is not a good way to load the image (for example, can lead to out of memory), what can I do to optimize it? The whole image needs to be loaded so user can scroll, edit on that image