29
29
* 4、多次setCompoundDrawablesRelative,图片会发生偏移 √
30
30
* 5、寻找一个合适的测量文字大小的时机,避免多次测量消耗性能 √
31
31
* 6、在draw时,避免用取出旧的drawable的bounds绘制,需要预先取出并存储起来,还需要注意在存储bounds时是不是有平移过 √
32
- * 7、
32
+ * 7、foreground会受平移影响 √
33
+ * 8、如果是只有hint没有Text需要也需要测量出文字大小√
33
34
*/
34
35
@ SuppressWarnings ({"UnusedReturnValue" , "unused" , "SameParameterValue" })
35
36
public class DrawableTextView extends AppCompatTextView {
@@ -118,6 +119,7 @@ protected void onLayout(boolean changed, int left, int top, int right, int botto
118
119
}
119
120
}
120
121
122
+
121
123
protected void onFirstLayout (int left , int top , int right , int bottom ) {
122
124
measureTextWidth ();
123
125
measureTextHeight ();
@@ -176,10 +178,16 @@ protected void onDraw(Canvas canvas) {
176
178
this .canvasTransY = transY ;
177
179
}
178
180
}
179
-
180
181
super .onDraw (canvas );
181
182
}
182
183
184
+ @ Override
185
+ public void onDrawForeground (Canvas canvas ) {
186
+ //再次平移回去
187
+ canvas .translate (-canvasTransX ,-canvasTransY );
188
+ super .onDrawForeground (canvas );
189
+ }
190
+
183
191
/**
184
192
* 计算drawable居中还需距离
185
193
* 如果左右两边都有图片,左图片居中则需要加上右侧图片占用的空间{@link #getCompoundPaddingEnd()},其他同理
@@ -219,7 +227,13 @@ protected int getCanvasTransY() {
219
227
protected void measureTextWidth () {
220
228
final Rect textBounds = new Rect ();
221
229
getLineBounds (0 , textBounds );
222
- final float width = getPaint ().measureText (getText ().toString ());
230
+ String text = "" ;
231
+ if (getText () != null && getText ().length () > 0 ) {
232
+ text = getText ().toString ();
233
+ } else if (getHint () != null && getHint ().length () > 0 ) {
234
+ text = getHint ().toString ();
235
+ }
236
+ final float width = getPaint ().measureText (text );
223
237
final float maxWidth = textBounds .width ();
224
238
mTextWidth = width <= maxWidth || maxWidth == 0 ? width : maxWidth ;
225
239
}
@@ -228,7 +242,8 @@ protected void measureTextWidth() {
228
242
* 获取文本的高度,通过{@link #getLineHeight}乘文本的行数
229
243
*/
230
244
protected void measureTextHeight () {
231
- if (getText ().length () > 0 )
245
+ if ((getText () != null && getText ().length () > 0 )
246
+ || (getHint () != null && getHint ().length () > 0 ))
232
247
mTextHeight = getLineHeight () * getLineCount ();
233
248
else
234
249
mTextHeight = 0 ;
0 commit comments