gpt4 book ai didi

android - 获取异步任务以加载位图的问题

转载 作者:搜寻专家 更新时间:2023-11-01 08:58:05 25 4
gpt4 key购买 nike

在出现内存不足错误后,我想使用 AsyncTask 加载我的位图,所以我从 Android 开发者网站获得了这段代码示例,但我在让所有东西协同工作时遇到了一些麻烦。

public class BitmapLoader {

public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;

if (height > reqHeight || width > reqWidth) {

// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);

// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}

return inSampleSize;
}

public static Bitmap decodeSampledBitmapFromResource(String orgImagePath,
int reqWidth, int reqHeight) {

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(orgImagePath, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(orgImagePath, options);
}

class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private int data = 0;

public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage
// collected
imageViewReference = new WeakReference<ImageView>(imageView);
}

// Decode image in background.
@Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
return decodeSampledBitmapFromResource(getResources(), data, 100,
100);
}

// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
}

我收到一个错误:方法 getResources() 没有为类型 BitmapLoader.BitmapWorkerTask 定义。我是 android 的新手,所以很可能我使用了错误的方法或其他东西,所以我希望有人能告诉我正确的用法,或者至少给我指出正确的方向。提前致谢。

link to the code i copied

最佳答案

您需要 Activity 上下文。将 Activity 上下文传递给 BitmapLoader 的构造函数。

     public class BitmapLoader {
Context context;
public BitmapLoader(Context mContext)
{
context = mContext;
}
}

使用context.getResources()

检查下面的链接

http://developer.android.com/reference/android/view/ContextThemeWrapper.html#getResources()

关于android - 获取异步任务以加载位图的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17433389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com