尝试模糊 Android 中的图像时出现问题

Issue with trying to Blur an image in Android

我正在尝试实施以下教程:https://www.youtube.com/watch?v=GJIXTm_MsbY

我按照说明创建了模糊 class:

public class BlurBuilder {

    private static final float BITMAP_SCALE = 0.1f;
    private static final float BLUR_RADIUS = 5.5f;

    public static Bitmap blur(Context context, Bitmap image) {

        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);

        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

        RenderScript rs = RenderScript.create(context);

        ScriptIntrinsicBlur scriptIntrinsicBlur = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));

        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);

        scriptIntrinsicBlur.setRadius(BLUR_RADIUS);
        scriptIntrinsicBlur.setInput(tmpIn);
        scriptIntrinsicBlur.forEach(tmpOut);

        tmpOut.copyTo(outputBitmap);

        return outputBitmap;

    }

}

然后我试图在我的 Adapter 视图中模糊图像,它使用 inflater 显示图像列表:

@Override
public void onBindViewHolder(GameViewHolder holder, int position) {

    final Games game = gameList.get(position);


    Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.forty);
    Bitmap blurredBitmap = BlurBuilder.blur(this, originalBitmap);


}

第一个问题是 getResources() 函数抛出错误

BlurBuilder.blur 函数中的 this 一样。

我不太确定如何解决这个问题,有人知道我做错了什么吗?

您无法直接访问回收器适配器中的 Context。通过 View 对象获取它。在您的情况下,您可以通过构造函数从 activity 传递上下文,例如:-

public class HomeActivity extends AppCompatActivity(){
 Context mContext;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        mContext = this;

        adapter = new HomeAdapter(mContext, arrayList);
    }
}

或者您可以尝试直接从 onBindViewHolder 访问 Like :-

@Override
public void onBindViewHolder(GameViewHolder holder, int position) {
    final Games game = gameList.get(position);

    Bitmap originalBitmap = BitmapFactory.decodeResource(holder.itemView.getContext().getResources(), R.drawable.forty);
    Bitmap blurredBitmap = BlurBuilder.blur(holder.itemView.getContext(), originalBitmap);

}