簡體   English   中英

如何使用畫布從圓內的字符串文本創建位圖?

[英]How to create bitmap from String text inside a circle using canvas?

我想獲得用戶姓名的縮寫,在ImageView上設置一個或一個帶有兩個或兩個字符的位圖,在一個圓圈內,如下所示:

在此處輸入圖片說明

我嘗試了一些在畫布上繪制圓和文本的方法,但無法正常工作。 我怎樣才能做到這一點?

您可以使用

public Bitmap createImage(int width, int height, int color, String name) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        Paint paint2 = new Paint();
        paint2.setColor(color);
        canvas.drawRect(0F, 0F, (float) width, (float) height, paint2);
        Paint paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setTextSize(72);
        paint.setTextScaleX(1);
        canvas.drawText(name, 75 - 25, 75 + 20, paint);
        return bitmap;
    }

我使用了TextDrawable庫,發現它非常有用。 這個輕量級的庫提供帶有字母/文本的圖像,例如Gmail應用程序。 它擴展了Drawable類,因此可以與現有/自定義/網絡ImageView類一起使用。 還包括用於創建可繪制對象的流暢界面和可自定義的ColorGenerator。

點擊此處查看github上的示例

圖像視圖設置圓形ImageView

ImageView imageView = (ImageView)findViewById(R.id.img);

imageView.setImageBitmap(ImageHelper.createImageRounded(getApplicationContext(), 150, 150, "S"));

使用畫布創建圓形圖像的方法

public static Bitmap createImageRounded(Context context, int width, int height, String name)
{
    Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(output);

    Paint paintCicle = new Paint();
    Paint paintText = new Paint();

    Rect rect = new Rect(0, 0, width, height);
    RectF rectF = new RectF(rect);
    float density = context.getResources().getDisplayMetrics().density;
    float roundPx = 100*density;

    paintCicle.setColor(Color.LTGRAY);
    paintCicle.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);

// Set Border For Circle
    paintCicle.setStyle(Paint.Style.STROKE);
    paintCicle.setStrokeWidth(4.0f);

    canvas.drawRoundRect(rectF, roundPx, roundPx, paintCicle);

    paintText.setColor(Color.GRAY);
    paintText.setTextSize(72);

    canvas.drawText(name, 75 - 23, 75 + 25, paintText);

    return output;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM