android: 在图像视图的中心绘制文本

android: draw text in center of imageview

我想在位图的中心将文本绘制到位图上。代码如下:

代码:

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 的中心。它位于右上角。如何让文字居中呢?谢谢

这将使文本位于中间:

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);