先来说一下FontMetrics这个类,这个类是关于字符属性和测量的类
用图可以更精确的知道各个属性的含义:
我们在Layout中有一个ImageView,我们可以通过:
<span style="white-space:pre"> </span>ImageView item_image = (ImageView)findViewById(R.id.item_image); item_image.setImageBitmap(makeMessageCenterIcon());
下面做一个这种效果的,特别适合有消息通知的icon:
代码可以这样来写:
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; }
android在如果绘制自定义的bitmap,然后返回给ImageView
原文地址:http://blog.csdn.net/baidu_nod/article/details/38167037