简体   繁体   中英

Paint onMeasure() decide height width

all

I am facing strange issue here, and I need expert advise on that.

I have a customview which is drawing a points and text along side it . Now my problem is that, i dont know its height of width at it will be count in onDraw method.(dynamic calculation of course). So how to do handle setMeasuredDimension(parentWidth, parentHeight) in this scenario. you do not know height and width, it will be calculated in onDraw depends on text length please help.

All you need to do is use [Paint.getTextWidths()]( https://developer.android.com/reference/android/graphics/Paint.html#getTextWidths(java.lang.String , float[])) in your onMeasure().

You'll get widths of all characters, so in a loop just add all the widths

float textWidth = 0;
float [] charsWidth = new float[text.length()];

int widths = mPaint.getTextWidths(text, charsWidth);

for (int i = 0; i < widths; i++) {
    textWidth += charsWidth[i];
}

and you have width of the text.

Don't forget to initialize the Paint object with the correct parameters, especially text size beforehand.

EDIT : if you need both text width and height then use instead Paint.getTextBounds() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM