java - 如何裁剪可绘制图像并将其设置为 View 的背景?

标签 java android xml drawable

我正在尝试获取壁纸图像并将其设置为 View 的背景。 我使用此代码将壁纸获取为 Drawable

Drawable bg = WallpaperManager.getInstance(getApplicationContext()).getDrawable();

现在我需要将此可绘制对象设置为我的View 的背景。很简单,就像

view.setBackground(bg);

但这会将整个壁纸设置为背景。我只想将一个特定区域(例如上半部分)设置为背景。我的问题是如何裁剪 Drawable 来完成此任务?提前致谢。

最佳答案

尝试将可绘制对象转换为位图并使用 setImageBitmap(DrawableAsBitmap)

如果您有 Drawable 作为资源,请尝试以下操作:

属性 位图bitmap_background; int 屏幕宽度 = 0; int 屏幕高度 = 0;

sizeScreen();
bitmap_background = decodeSampledBitmapFromResource(getResources(),   R.drawable.your_resource, screenWidth, screenHeight);
view.setImageBitmap(bitmap_background);

private void sizeScreen() {
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    screenHeight = displaymetrics.heightPixels;
    screenWidth = displaymetrics.widthPixels;
}

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
                                                     int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

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;
}

关于java - 如何裁剪可绘制图像并将其设置为 View 的背景?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35774834/

相关文章:

java - 使用 Java ImageIO 或 Imagemagick 将 DCI-P3 色彩空间转换为 sRGB

java - UIMA RUTA - 如何组合注释?

Java 通配符通用作为 Eclipse 和 SonarQube 中的返回警告

android - 在 Composable 函数之外引用或枚举 Jetpack Compose MaterialTheme 主题颜色

android - 需要首先通过缓冲而不下载完整视频来在 videoview 中播放视频。有这方面的图书馆吗?

python - 使用 REGEX 通过脚本检查 XML 节点

Perl 中的 XML Pull 解析器实现?

java - 游戏框架 2.2 java : how to set language (i18n) from subdomain

android - 使用 AsyncTask 从解析的 JSON 对象中设置文本

mysql - 开始学习 Actionscript 3.0 的教程?