Convert String to Drawable

后端 未结 8 2283
我在风中等你
我在风中等你 2021-02-20 12:31

I want to raise a notification showing an icon in the status bar - so far so good, but actually I would like this icon to be a 3 character String.

So my question is: Is

8条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-20 13:31

    (I know this doesn't answer the OP's question fully, but the title got me here since it's pretty general.)

    After fiddling around a bit, I've come up with this solution. It's pretty messy and could probably be improved, but it works.

    In its current form, the function takes the first letter of the String it's passed and a unique ID for that String. The ID is only used for background color generation and remembering it, so it can be removed if you're going to use a steady color.

    I made this to generate default images for contacts that don't have images saved, but it should be easy to adapt. It also happens to return an InputStream instead of a Drawable, but you can either just return bitmap after drawing to it, or use 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);
    }
    

提交回复
热议问题