方法实现如下:
package com.example.mytest;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.test);
Thread thread = new Thread() {
@Override
public void run() {
Drawable mPointMenuBmp = initCounterResources(3);
Message message = handler.obtainMessage();
message.what = 1;
message.obj = mPointMenuBmp;
handler.sendMessage(message);
super.run();
}
};
thread.start();
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Drawable mPointMenuBmp = (Drawable) msg.obj;
mTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, mPointMenuBmp, null);
super.handleMessage(msg);
}
};
/** <br>功能简述:画出小红点
* <br>功能详细描述:
* <br>注意:
* @param count
*/
private Drawable initCounterResources(int count) {
Drawable mCounterDrawable = null;
Bitmap bitmapDrawable = null;
if (mCounterDrawable == null) {
// 初始化画布
mCounterDrawable = getResources().getDrawable(R.drawable.go_account_stat_notify);
Bitmap bitmapDrawables = ((BitmapDrawable) mCounterDrawable).getBitmap();
int bitmapX = bitmapDrawables.getWidth();
int bitmapY = bitmapDrawables.getHeight();
bitmapDrawable = Bitmap.createBitmap(bitmapX, bitmapY, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapDrawable);
// 拷贝图片
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setDither(true);// 防抖动
mPaint.setFilterBitmap(true);// 用来对Bitmap进行滤波处理,这样,当你选择Drawable时,会有抗锯
Rect src = new Rect(0, 0, bitmapX, bitmapX);
Rect dst = new Rect(0, 0, bitmapX, bitmapX);
canvas.drawBitmap(((BitmapDrawable) mCounterDrawable).getBitmap(), src, dst, mPaint);
// canvas.drawBitmap(bitmapDrawable, bitmapX, bitmapY, mPaint);
//画数字
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTypeface(Typeface.DEFAULT_BOLD);
mPaint.setColor(Color.BLACK);
mPaint.setTextSize(20);
FontMetrics fontMetrics = mPaint.getFontMetrics();
canvas.drawText(String.valueOf(count), 56, 56 + (fontMetrics.bottom - fontMetrics.top) / 4, mPaint);
canvas.save();
}
return new BitmapDrawable(getResources(), bitmapDrawable);
}
}