Android 如何将图像设置为圆形?
我在前面的一个主题中发现了以下代码:Android 如何将图像设置为圆形?,android,Android,我在前面的一个主题中发现了以下代码: public Bitmap getLetterTile(String displayName, String key, int width, int height) { final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); final char firstChar = displayName.trim().
public Bitmap getLetterTile(String displayName, String key, int width, int height) {
final Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final char firstChar = displayName.trim().charAt(0);
final Canvas c = mCanvas;
c.setBitmap(bitmap);
c.drawColor(pickColor(key));
mFirstChar[0] = Character.toUpperCase(firstChar);
mPaint.setTextSize(mTileLetterFontSize);
mPaint.getTextBounds(mFirstChar, 0, 1, mBounds);
c.drawText(mFirstChar, 0, 1, width / 2, height / 2 + (mBounds.bottom - mBounds.top) / 2, mPaint);
return bitmap;
}
private int pickColor(String key) {
final int color = Math.abs(key.hashCode()) % NUM_OF_TILE_COLORS;
try {
return mColors.getColor(color, Color.BLACK);
} finally {
mColors.recycle();
}
}
public Bitmap getCircularBitmap(Bitmap bitmap) {
Bitmap output;
if (bitmap.getWidth() > bitmap.getHeight()) {
output = Bitmap.createBitmap(bitmap.getHeight(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
} else {
output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getWidth(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
float radius = 0;
if (bitmap.getWidth() > bitmap.getHeight()) {
radius = bitmap.getHeight() / 2;
} else {
radius = bitmap.getWidth() / 2;
}
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(radius, radius, radius, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
它基本上是用菜单中名字的第一个字母创建一个圆圈。如果getLetterTile
失败,我希望它设置一个默认方法。如果displayName
为空,则可能会失败。我有一个配置文件默认的头像图片,但我希望它在一个圆圈内,因为图像不在圆圈内:
如何使用默认图像并将其设置为圆形
在XML中:
<ImageView
android:id="@+id/user_avatar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
来自您所说的XML?
试试下面
<androidx.cardview.widget.CardView
app:cardCornerRadius="35dp"
app:cardElevation="0dp"
android:layout_width="70dp"
android:layout_height="70dp">
<ImageView
android:id="@+id/user_avatar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:srcCompat="@drawable/pro_pic"
android:scaleType="fitXY"
android:contentDescription="@string/todo" />
</androidx.cardview.widget.CardView>
有两个github存储库可以实现您所需的功能。因此,请尝试使用它们。检查此使用图像加载程序库。例如,Glide,Picasso正如您从代码中看到的,我已经有了一个方法
getCircularBitmap
来获取位图。我只希望它设置一个图像,而不是默认的字母。无需使用三方库或编辑XML。
implementation "androidx.cardview:cardview:1.0.0"