0

我正在从图库中将背景图像设置为线性布局,除非图像尺寸太大,否则它工作正常,我已经实现了异常处理,如果有任何异常,那么我正在从资源设置默认背景,但仍然是我的应用程序正在崩溃。这是我的代码...

  public static void setBackgroundImage(Context context,
        LinearLayout linearLayout, Uri uri) {

    try {
        Bitmap bitmap = BitmapFactory.decodeStream(context
                .getContentResolver().openInputStream(uri));
        Drawable drawable = new BitmapDrawable(context.getResources(),
                bitmap);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            setImageForJellyBeanOrLater(linearLayout, drawable);
        } else {
            linearLayout.setBackgroundDrawable(drawable);
        }

    } catch (Exception e) {
        linearLayout.setBackgroundResource(R.drawable.ic_bg_image);
        e.printStackTrace();
    }
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private static void setImageForJellyBeanOrLater(LinearLayout linearLayout,
        Drawable drawable) {
    linearLayout.setBackground(drawable);
}
4

1 回答 1

1

这里的问题是您从图库中选择的图像应该被裁剪。

试试下面的代码,它对我有用。

获取布局的大小:

    final int width = frm_layout.getWidth();
    final int height = frm_layout.getHeight();

然后使用下面的压缩,

    thumbnail = (BitmapFactory.decodeFile(ImagePath));
    thumbnail = Bitmap.createScaledBitmap(thumbnail, width, height ,true);
于 2013-12-02T13:22:23.577 回答