android在假设绘制自己定义的bitmap,然后返回给ImageView

时间:2021-01-28 02:02:46

先来说一下FontMetrics这个类。这个类是关于字符属性和測量的类

android在假设绘制自己定义的bitmap,然后返回给ImageView

用图能够更精确的知道各个属性的含义:

android在假设绘制自己定义的bitmap,然后返回给ImageView

我们在Layout中有一个ImageView,我们能够通过:

<span style="white-space:pre">		</span>ImageView item_image = (ImageView)findViewById(R.id.item_image);
item_image.setImageBitmap(makeMessageCenterIcon());

这样的方式来把bitmap来填入ImageView

以下做一个这样的效果的。特别适合有消息通知的icon:

android在假设绘制自己定义的bitmap,然后返回给ImageView

代码能够这样来写:

protected Bitmap makeMessageCenterIcon(){
int mMsgCnt = 4;
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.desktop_messageicon);
if(icon == null){
return icon;
} //make notice icon
if(mMsgCnt > 0) {
Bitmap noticeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.notice_count_bg);
if(noticeIcon != null){
int h = noticeIcon.getHeight();
int w = noticeIcon.getWidth(); Bitmap noticeIconBmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);//noticeIconBmp是终于须要的画字的bitmap
Canvas noticeCanvas = new Canvas(noticeIconBmp);
Paint noticeCntpaint = new Paint();
noticeCntpaint.setAntiAlias(true);
noticeCanvas.drawBitmap(noticeIcon, 0, 0, noticeCntpaint);
noticeCntpaint.setTextAlign(Align.CENTER);
noticeCntpaint.setColor(getResources().getColor(R.drawable.white)); FontMetrics fontMetrics = noticeCntpaint.getFontMetrics();
float x = noticeIcon.getWidth() / 2;
float y = (noticeIcon.getHeight() - fontMetrics.ascent) / 2 - 2; //fontMetrics是在baseline以上的字符最高处的位置
noticeCanvas.drawText(String.valueOf(mMsgCnt), x, y, noticeCntpaint); //在canvas上的(x,y)的位置上写mMsgCnt //draw notice icon onto message icon
h = icon.getHeight();
w = icon.getWidth();
Bitmap iconBmp = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(iconBmp); Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawBitmap(icon, 0, 0, paint);
float left = icon.getWidth() - noticeIcon.getWidth();
float top = 0;
canvas.drawBitmap(noticeIconBmp, left, top, paint); return iconBmp;
}
}
return icon; }