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

标签 android android-layout

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/

    相关文章:

    java - 如何将变量从 Activity 传递到 fragment 无法解决上一个问题的所有问题

    android - surfaceDestroyed() 什么时候发生

    android - 在测试 : "Method putExtra in android.content.Intent not mocked" 中创建 Intent

    android - NestedScrollView中如何实现ConstraintLayout

    android - 使用 TabHost 时如何消除像素错误

    android - Android Fragments 中方向改变时的布局改变

    android - 具有不同页面布局的 viewpager 的操作栏选项卡

    java - 如何将用户电子邮件从 Firebase 身份验证检索到实时数据库

    java - 无法验证来自 RxJava 订阅者的模拟方法调用

    android - 如何分享imageview的图像?