Android:在imageview的中心绘制文本

时间:2019-06-17 17:26:36

标签: android canvas text 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的中心。它位于右上角。如何使文本居中?谢谢。

1 个答案:

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