我想在位图的中心将文本绘制到位图上。代码如下:
public static ImageView getBallwithText(Activity act, String isSpecial, String text, String textColor, int maxWidth, int maxHeight)
{
Bitmap jungle01 = null;
Bitmap jungle02 = null;
if (isSpecial.equals("special"))
{
jungle02= BitmapFactory.decodeResource(act.getResources(), Constants.ball_template_1[1]).copy(Bitmap.Config.ARGB_8888, true);
}
else
{
jungle01= BitmapFactory.decodeResource(act.getResources(), Constants.ball_template_1[0]).copy(Bitmap.Config.ARGB_8888, true);
}
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(act.getResources().getColor(android.R.color.white));
paint.setTextSize((maxHeight/3));
Canvas cc;
if (isSpecial.equals("special"))
{
cc = new Canvas(jungle02);
cc.drawText(""+text, jungle02.getHeight()/2, jungle02.getHeight()/2, paint);
}
else
{
cc = new Canvas(jungle01);
cc.drawText(""+text, jungle01.getHeight()/2, jungle01.getHeight()/2, paint);
}
ImageView iv = new ImageView(act);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(maxWidth, maxHeight);
iv.setLayoutParams(layoutParams);
iv.setBackgroundColor(Color.TRANSPARENT);
if (isSpecial.equals("special"))
{
iv.setImageBitmap(jungle02);
}
else
{
iv.setImageBitmap(jungle01);
}
iv.setScaleType(ImageView.ScaleType.FIT_XY);
iv.setMaxHeight(maxHeight);
iv.setMaxWidth(maxWidth);
return iv;
}
文本不在创建的ImageView的中心。它位于右上角。如何使文本居中?谢谢。
答案 0 :(得分:0)
这会使文本居中:
cc = new Canvas(jungle02);
int xPos = (cc.getWidth() / 2);
int yPos = (int) ((cc.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 2)) ;
cc.drawText(""+text, xPos, yPos, paint);