我正在将drawable转换为可静态位图,在其上创建画布和绘制文本,将画布添加到图像,然后将位图保存到文件中。它正确保存图像,但文本不在保存的图像上。我已经查看了其他答案并尝试了它们,但似乎没有任何工作。
这是代码:
public void createTitleImageFromDrawable(){
// Create file object for saving the the bitmap
File file = new File(MainActivity.mRootDirectoryForFrontViewImages + "front_view_image_day00001.PNG");
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create a bitmap from the title image drawable
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.dory);
// Create a mutable version of the bitmap to draw on it
Bitmap mutableBitmap = bm.copy(Bitmap.Config.ARGB_8888, true);//<--true makes copy mutable
// Create a new canvas and set it to the new muteable bitmap
Canvas canvas = new Canvas(mutableBitmap);
// Create paint object and set up settings for it
Paint paint = new Paint();
paint.setColor(Color.BLACK); // Text Color
paint.setTextSize(40); // Text Size
// Using the canvas draw on the muteable bitmap
canvas.drawText("Test", 10, 10, paint);
// Put the muteable file into the file
mutableBitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
感谢您的帮助。
答案 0 :(得分:0)
在这里,我提供的代码对您有所帮助。请理解此代码并根据您的要求应用更改。您可以将文本的确切位置放在您触摸的位置。
public void setCBitmap(Bitmap bitmap2, MotionEvent e, String name) {
float eventX = e.getX();
float eventY = e.getY();
float[] eventXY = new float[] { eventX, eventY };
Matrix invertMatrix = new Matrix();
((ImageView) main_iMG).getImageMatrix().invert(invertMatrix);
invertMatrix.mapPoints(eventXY);
int x = Integer.valueOf((int) eventXY[0]);
int y = Integer.valueOf((int) eventXY[1]);
Canvas canvas = null;
canvas = new Canvas(bitmap2);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.WHITE);
paint.setTextSize(45);
Paint mpaint= new Paint();
mpaint.setColor(Color.parseColor("#f9bf3a"));
mpaint.setStyle(Style.FILL);
float w = paint.measureText(name)/2;
float textSize = paint.getTextSize();
Paint paint1= new Paint(Paint.ANTI_ALIAS_FLAG);
Paint p= new Paint();
p.setAntiAlias(true);
p.setColor(Color.WHITE);
p.setStyle(Paint.Style.FILL);
canvas.drawARGB(0, 0, 0, 0);
canvas.drawRoundRect(new RectF( x-13, y -(textSize+3), x + paint.measureText(name)+13,y+23), 7, 7, p);
canvas.drawRoundRect(new RectF( x-10, y -(textSize), x + paint.measureText(name)+10,y+20), 7,7,mpaint);
canvas.drawText(name, x, y, paint);
main_iMG.setImageBitmap(bitmap2)}