(我知道这并不能完全回答 OP 的问题,但标题让我来到这里,因为它很笼统。)
在摆弄了一下之后,我想出了这个解决方案。它相当混乱,可能会改进,但它确实有效。
在其当前形式中,该函数采用它传递的字符串的第一个字母和该字符串的唯一 ID。 ID 仅用于背景颜色的生成和记忆,因此如果您要使用稳定的颜色,可以将其删除。
我这样做是为了为没有保存图像的联系人生成默认图像,但它应该很容易适应。它也恰好返回一个 InputStream 而不是一个 Drawable,但你可以在绘制到它之后只返回 bitmap,或者使用 Drawable.createFromStream()。
private static InputStream returnDefaultContact(Context context, String name, long id) {
Paint textPaint = new Paint();
textPaint.setColor(Color.WHITE);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(110);
int color = PreferenceManager.getDefaultSharedPreferences(context).getInt("contact_by_id_" + id, 0);
if (color == 0) {
int colorValue1 = (int)((56 + Math.random() * 200));
int colorValue2 = (int)((56 + Math.random() * 200));
int colorValue3 = (int)((56 + Math.random() * 200));
color = Color.rgb(colorValue1, colorValue2, colorValue3);
PreferenceManager.getDefaultSharedPreferences(context).edit().putInt("contact_by_id_" + id, color).apply();
}
Paint backgroundPaint = new Paint();
backgroundPaint.setColor(color);
Bitmap bitmap = Bitmap.createBitmap(120, 120, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, canvas.getHeight() / 2, backgroundPaint);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
canvas.drawText(name.substring(0, 1), xPos, yPos, textPaint);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
return new ByteArrayInputStream(imageInByte);
}