在开发中可能需要用到一些带数字的drawable图片,比如从0-99,此时让UI挨个给图,就很没有必要了。资源文件也会爆棚。
此时就需要我们用代码自定义drawable图片来。先看效果:
上代码:
package com.everbridge.xxx.util;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
/**
* Created by maple on 16/11/14.
*/
public class BitmapUtils {
public static Bitmap getNumberBitmap(int iconSize, String number) {
return getNumberBitmap(iconSize, iconSize / 10, number);
}
public static Bitmap getNumberBitmap(int iconSize, int padding, String number) {
Bitmap bitmap = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
RectF rect = new RectF(0, 0, canvas.getWidth(), canvas.getHeight());
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
// draw background
paint.setColor(Color.WHITE);
canvas.drawOval(rect, paint);
paint.setColor(Color.RED);
canvas.drawOval(new RectF(padding, padding, rect.width() - padding, rect.height() - padding), paint);
// draw text
paint.setColor(Color.WHITE);
paint.setStrokeWidth(3);
paint.setTextSize(iconSize * 0.6f);
paint.setTextAlign(Paint.Align.CENTER);
Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
float baseline = (rect.bottom + rect.top - fontMetrics.bottom - fontMetrics.top) / 2;
canvas.drawText(number, rect.centerX(), baseline, paint);
return bitmap;
}
}