1

我正在尝试制作一个应用程序,当应用程序打开时,它会在后台显示不同的图像,但是当我尝试调用该方法时。我收到错误。我正在为低于 16 的 api 制作模糊图像,这是我使用的

public class MainActivity extends AppCompatActivity {
int roll[]={R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,R.drawable.img5,R.drawable.img6};
int number;
private final Paint mPaint = new Paint();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Random num= new Random();
number=num.nextInt(6);
    ImageView img =(ImageView)findViewById(R.id.imageView);

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),roll[number]);
    Bitmap blurredBitmap = blur(""+roll[number]);
    img.setImageBitmap(blurredBitmap);
}


public Bitmap blur(final String pathToBitmap) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    final Bitmap normalOne = BitmapFactory.decodeFile(pathToBitmap, options);
    final Bitmap resultBitmap = Bitmap.createBitmap(options.outWidth, options.outHeight, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(resultBitmap);
    mPaint.setAlpha(180);
    canvas.drawBitmap(normalOne, 0, 0, mPaint);
    int blurRadius = 12;
    for (int row = -blurRadius; row < blurRadius; row += 2) {
        for (int col = -blurRadius; col < blurRadius; col += 2) {
            if (col * col + row * row <= blurRadius * blurRadius) {
                mPaint.setAlpha((blurRadius * blurRadius) / ((col * col + row * row) + 1) * 2);
                canvas.drawBitmap(normalOne, row, col, mPaint);
            }
        }
    }
    normalOne.recycle();
    return resultBitmap;
}
}

我在哪里做错了?我正在使用这种方法,因为在 google 中,大多数模糊效果在 api<16 中不起作用。只想知道我在代码中做错了什么。

4

1 回答 1

2

当您尝试使用此代码时:

位图 blurredBitmap = blur(""+roll[number]);

此路径( ""+roll[number] ) 与绝对路径不匹配,因为可绘制资源是在运行时添加到二进制文件中的,因此无法通过路径访问。尝试使用

BitmapFactory.decodeResource(getResources(),resourceID);

 public Bitmap blur(int resourceId) {
        final Bitmap normalOne = BitmapFactory.decodeResource(getResources(),resourceId);
        final Bitmap resultBitmap = Bitmap.createBitmap(normalOne.getWidth(), normalOne.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(resultBitmap);
        mPaint.setAlpha(180);
        canvas.drawBitmap(normalOne, 0, 0, mPaint);
        int blurRadius = 12;
        for (int row = -blurRadius; row < blurRadius; row += 2) {
            for (int col = -blurRadius; col < blurRadius; col += 2) {
                if (col * col + row * row <= blurRadius * blurRadius) {
                    mPaint.setAlpha((blurRadius * blurRadius) / ((col * col + row * row) + 1) * 2);
                    canvas.drawBitmap(normalOne, row, col, mPaint);
                }
            }
        }
        normalOne.recycle();
        return resultBitmap;
    }
于 2016-06-02T14:32:15.893 回答