When adding an adaptive icon to an ImageView
in an Activity in Android, it seems to adopt the same version as OEM design. In my case right now this is the rounded version. But I want to display this as an icon in my main activity and thus want to use for example the square version with rounded corners. If this is possible, how can I achieve this? If this is not possible I can create a new resource, but it needs to use ic_launcher_background
and ic_launcher_foreground
so that the icon is not defined in multiple places.
This is my 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>
This is my ImageView
:
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
Before telling the solution directly, you'd know how system draw an adaptive icon in a image view. It mainly contains three steps.
If you put an adaptive icon into an ImageView
, this steps will be completed automatically. Hence there will be a system defined mask on that. So your question is how to draw a customized mask there. Then let's see how we can achieve this.
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
used for drawing drawable layers. Canvas canvas = new Canvas(bitmap);
background.setBounds(0, 0, bitmapSize, bitmapSize);
background.draw(canvas);
foreground.setBounds(0, 0, bitmapSize, bitmapSize);
foreground.draw(canvas);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.