1. 效果图

原图:

2.主要代码
public class MainActivity extends Activity {
ImageView img;
private Bitmap imgMarker;
private int width,height; //图片的高度和宽带
private Bitmap imgTemp; //临时标记图
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imt_test);
imgMarker = BitmapFactory.decodeResource(getResources(), R.drawable.icon_tag);
width = imgMarker.getWidth();
height = imgMarker.getHeight();
img.setBackgroundDrawable(createDrawable('A'));
}
// 穿件带字母的标记图片
private Drawable createDrawable(char letter) {
imgTemp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(imgTemp);
Paint paint = new Paint(); // 建立画笔
paint.setDither(true);
paint.setFilterBitmap(true);
Rect src = new Rect(0, 0, width, height);
Rect dst = new Rect(0, 0, width, height);
canvas.drawBitmap(imgMarker, src, dst, paint);
Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG
| Paint.DEV_KERN_TEXT_FLAG);
textPaint.setTextSize(20.0f);
textPaint.setTypeface(Typeface.DEFAULT_BOLD); // 采用默认的宽度
textPaint.setColor(Color.WHITE);
canvas.drawText(String.valueOf(letter), width /2-5, height/2+5,
textPaint);
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
return (Drawable) new BitmapDrawable(getResources(), imgTemp);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
测试通过,可以使用
源码下载地址: 点击打开链接
这篇博客介绍了如何在Android应用中实现图片添加文字的功能。通过提供主要代码段,展示了创建带有指定字符的标记图片的过程,包括使用Bitmap、Canvas和Paint进行绘制。
4917

被折叠的 条评论
为什么被折叠?



