Letter avatar like Gmail Android best practice

后端 未结 4 1955
既然无缘
既然无缘 2020-12-17 05:30

What is the best way of generating (in code) a letter avatar like in Gmail? Here you have an example https://drive.google.com/folderview?id=0B0Fhz5fDg1njSmpUakhhZllEWHM&

4条回答
  •  孤城傲影
    2020-12-17 06:22

    This is what I've used once.. please try and modify according to your requirements.

        public class LetterAvatar extends ColorDrawable {
    Paint               paint   = new Paint();
    Rect                bounds  = new Rect();
    
    String              pLetters;
    private float       ONE_DP  = 0.0f;
    private Resources   pResources;
    private int         pPadding;
    int                 pSize   = 0;
    float               pMesuredTextWidth;
    
    int                 pBoundsTextwidth;
    int                 pBoundsTextHeight;
    
    public LetterAvatar (Context context, int color, String letter, int paddingInDp) {
        super(color);
        this.pLetters = letter;
        this.pResources = context.getResources();
        ONE_DP = 1 * pResources.getDisplayMetrics().density;
        this.pPadding = Math.round(paddingInDp * ONE_DP);
    }
    
    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        paint.setAntiAlias(true);
    
    
    
        do {
            paint.setTextSize(++pSize);
            paint.getTextBounds(pLetters, 0, pLetters.length(), bounds);
    
        } while ((bounds.height() < (canvas.getHeight() - pPadding)) && (paint.measureText(pLetters) < (canvas.getWidth() - pPadding)));
    
        paint.setTextSize(pSize); 
        pMesuredTextWidth = paint.measureText(pLetters);
        pBoundsTextHeight = bounds.height();
    
        float xOffset = ((canvas.getWidth() - pMesuredTextWidth) / 2);
        float yOffset = (int) (pBoundsTextHeight + (canvas.getHeight() - pBoundsTextHeight) / 2);
        paint.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
        paint.setColor(0xffffffff);
        canvas.drawText(pLetters, xOffset, yOffset, paint);
    }
        }
    

    then set new LetterAvatar(context, colorCode, letters, padding) in your imageview.setdrawable

提交回复
热议问题