开发者

Center text on image in android?

开发者 https://www.devze.com 2023-04-01 17:50 出处:网络
In my android app I need to display a text on an image. The text is entered by user in an alertDialog. This text I need to center it on the bottom of the image. I draw the text on image with this :

In my android app I need to display a text on an image. The text is entered by user in an alertDialog. This text I need to center it on the bottom of the image. I draw the text on image with this :

private Canvas drawTextImage(Bitmap b) {
        Canvas c = new Canvas(b);
        Paint paint = new Paint();
        paint.setColor(getResources().getColor(R.color.orange));

        paint.setStrokeWidth(30);
        paint.setAntiAlias(true);
        paint.setTextSize(40);
        c.drawText(text, 350, 900, paint);

        c.translate(300, 50);
        return c;
    }

My alertDiallg is this :

        final AlertDialog.Builder alert = new AlertDialog.Builder(this);
    alert.setTitle("Enter a text ");
    final EditText input = new EditText(this);
    InputFilter[] FilterArray = new InputFilter[1];
    FilterArray[0] = new InputFilter.LengthFilter(25);
    input.setFilters(FilterArray);

    alert.setView(input);
    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public开发者_如何转开发 void onClick(DialogInterface dialog, int whichButton) {
            text = input.getText().toString().trim();
            Canvas c = new Canvas(bitmapResult);
            drawTextImage(bitmapResult);
            saveimage();
        }
    });

    alert.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    dialog.cancel();
                    saveimage();
                }
            });

    alert.show();

Tehe text has to be center according to it's length. How can I do this?

Thanks in advance..


Use

Paint.setTextAlign(Paint.Align.CENTER);

on the paint thats used to draw your text.

public void setTextAlign (Paint.Align align)

Set the paint's text alignment. This controls how the text is positioned relative to its origin. LEFT align means that all of the text will be drawn to the right of its origin (i.e. the origin specifieds the LEFT edge of the text) and so on.

Source


Edit: In draw text you have to specify half the with of your image as the x-coordinate (center), the y-coordinate should stay the same (somewhere along the bottom, depending how high you want it).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号