gpt4 book ai didi

android - 在 Android 上将某些版本的自适应图标显示为 ImageView

转载 作者:行者123 更新时间:2023-12-05 00:04:43 24 4
gpt4 key购买 nike

ImageView 添加自适应图标时在 Android 的一个 Activity 中,它似乎采用了与 OEM 设计相同的版本。就我现在而言,这是圆形版本。但我想在我的主要 Activity 中将其显示为一个图标,因此想使用例如带圆角的方形版本。如果这是可能的,我怎样才能做到这一点?如果这不可能,我可以创建一个新资源,但它需要使用 ic_launcher_backgroundic_launcher_foreground这样图标就不会在多个地方定义。
这是我的ic_launcher.xml :

<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
这是我的 ImageView :
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />

最佳答案

在直接告诉解决方案之前,您会知道系统如何在 ImageView 中绘制自适应图标。它主要包含三个步骤。

  • 画一个背景。
  • 画一个前景。
  • 使用蒙版设置透明区域。

  • 如果您将自适应图标放入 ImageView ,此步骤将自动完成。因此,将有一个系统定义的掩码。所以你的问题是如何在那里画一个定制的面具。那么让我们看看我们如何实现这一点。
  • 获取自适应可绘制对象及其图层。
  •     Drawable rawDrawable = getResources().getDrawable(R.mipmap.ic_launcher, null);
    Drawable foreground = rawDrawable.getForeground();
    Drawable background = rawDrawable.getBackground();
  • 创建具有自定义大小的位图。
  •     Bitmap bitmap = Bitmap.createBitmap(bitmapSize, bitmapSize, Bitmap.Config.ARGB_8888);
  • 创建 Canvas用于绘制可绘制图层。
  •     Canvas canvas = new Canvas(bitmap);
  • 绘制图层。
  •     background.setBounds(0, 0, bitmapSize, bitmapSize);
    background.draw(canvas);
    foreground.setBounds(0, 0, bitmapSize, bitmapSize);
    foreground.draw(canvas);
  • 在第 4 步之后,您将获得一个方形图标。如果您需要为其添加圆角。你需要自己画面具。
  •     Bitmap maskBitmap = Bitmap.createBitmap(bitmapSize, bitmapSize, Bitmap.Config.ARGB_8888);
    Canvas maskCanvas = new Canvas(maskBitmap);

    Paint xferPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    xferPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    xferPaint.setColor(Color.RED);
    maskCanvas.drawRoundRect(0,0,bitmapSize, bitmapSize, 12, 12, xferPaint);

    xferPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
    canvas.drawBitmap(maskBitmap, 0, 0, xferPaint);
  • 然后把位图放到ImageView ,
  •     ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);

    关于android - 在 Android 上将某些版本的自适应图标显示为 ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62613293/

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