繁体   English   中英

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

[英]Display certain version of adaptive icon as ImageView on Android

ImageView中的Activity中为ImageView添加自适应图标时,似乎采用与OEM设计相同的版本。 就我现在而言,这是圆形版本。 但我想在我的主要活动中将其显示为一个图标,因此想使用例如带圆角的方形版本。 如果这是可能的,我怎样才能做到这一点? 如果这不可能,我可以创建一个新资源,但它需要使用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" />

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

  1. 画一个背景。
  2. 画一个前景。
  3. 使用蒙版设置透明区域。

如果将自适应图标放入ImageView中,此步骤将自动完成。 因此,将有一个系统定义的掩码。 所以你的问题是如何在那里画一个定制的面具。 那么让我们看看我们如何实现这一点。

  1. 获取自适应可绘制对象及其图层。
    Drawable rawDrawable = getResources().getDrawable(R.mipmap.ic_launcher, null);
    Drawable foreground = rawDrawable.getForeground();
    Drawable background = rawDrawable.getBackground();
  1. 创建具有自定义大小的 bitmap。
    Bitmap bitmap = Bitmap.createBitmap(bitmapSize, bitmapSize, Bitmap.Config.ARGB_8888);
  1. 创建用于绘制可绘制图层的Canvas
    Canvas canvas = new Canvas(bitmap);
  1. 绘制图层。
    background.setBounds(0, 0, bitmapSize, bitmapSize);
    background.draw(canvas);
    foreground.setBounds(0, 0, bitmapSize, bitmapSize);
    foreground.draw(canvas);
  1. 在第 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);
  1. 然后将 bitmap 放入ImageView
    ((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM