我尝试在第一个图像编辑器应用程序中将位图加载到自定义SurfaceView。它将尝试缩放图像(向上或向下)以适应屏幕高度(是的,我知道它是愚蠢的功能,但我也在学习android)。这是活动中的代码
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);
}
这是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);
}
}
如果我尝试放大,比如从1280 * 800到2048 * 1280,那么SurfaceView会愉快地加载我的缩放位图
但是,如果我尝试从3264 * 1840缩小到2270 * 1280,我最终会出现黑屏
我的问题是:
答案 0 :(得分:1)
在Android上使用bitmap
或任何类型的图片时,最大的风险之一是OutOfMemoryError
,当您进行测试时,可能不会出现这种风险。由于Android设备中缺少Memory
avaialable。
在SO和Android页面上已经多次讨论过这个问题 参考
我个人最喜欢的解决图像问题的方法是使用ImageLoader。尝试浏览ImageLoader
,这是最好的。
PS:我的应用加载了大约50-100张图片到ListView
。永远不会崩溃。