我有一个图像视图,其中有一个图像设置要显示,图像视图设置为在宽度和高度上匹配父图像,但是当包含图像的片段可见时,整个应用程序都会滞后,因为它似乎要在每次重绘时重新缩放图像,在较旧的设备上有日志,图像无法在2048x2048上缩放,但我最近无法重现此错误。
有什么方法可以解决这个问题吗?我尝试创建一个只需要缩放图像一次的自定义图像视图,但在多次使用时会导致OutOfMemoryException,因此我更喜欢使用普通ImageView的解决方案。
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background"/>
<com.app.myapp.ScaledImageView
android:id="@+id/scaledImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"/>
public class ScaledImageView extends View
{
private Bitmap bitmap;
public ScaledImageView(Context context)
{
super(context);
}
public ScaledImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public void setImageResource(int resId)
{
bitmap = BitmapFactory.decodeResource(getContext().getResources(), resId);
}
@Override
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
if (bitmap != null)
canvas.drawBitmap(bitmap, 0, 0, null);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
try
{
Bitmap tmp = Bitmap.createScaledBitmap(bitmap, w, h, false);
bitmap.recycle();
bitmap = tmp;
} catch (Exception e)
{
e.printStackTrace();
}
}
@Override
protected void onDetachedFromWindow()
{
super.onDetachedFromWindow();
bitmap = null;
}
}