我跑你的代碼,並立即得到了Lint
錯誤。在init()
中,您將mTextPaint
設置爲android.R.color.black
。因爲它是一個靜態值,我可以立即看到該變量的實際值int
是0x0106000c
,這是幾乎完全透明的。你應該使用getResources().getColor(android.R.color.black)
或普通的'Color.BLACK
。
注意12的textSize
是非常非常小的。此代碼顯示12(儘管非常小)。
public class MyImageView extends ImageView {
public MyImageView(Context context, AttributeSet attributeSet, int defStyle) {
super(context, attributeSet, defStyle);
init();
}
public MyImageView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
init();
}
public MyImageView(Context context) {
super(context);
init();
}
Paint mTextPaint;
private void init() {
mTextPaint = new Paint();
mTextPaint.setColor(Color.BLACK);
mTextPaint.setTextSize(12);
mTextPaint.setTextAlign(Paint.Align.LEFT);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int imgWidth = getMeasuredWidth();
int imgHeight = getMeasuredHeight();
float txtWidth = mTextPaint.measureText("your text");
int x = Math.round(imgWidth/2 - txtWidth/2);
int y = imgHeight/2 - 6;
canvas.drawText("12", x, y, mTextPaint);
}
}
XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.example.mytest.MyImageView
android:layout_width="100dp"
android:layout_height="100dp"/>
</RelativeLayout>
複製/粘貼,如果問題仍然存在,開始記錄。再次,這個代碼的作品,我看到我的屏幕上12
。
我懷疑它與dp和像素有關,因爲'setTextSize'在dp中,'imgWidth','imgHeight'以像素爲單位。並記錄'imgWidth'和'imgHeight'的值。 – stealthjong
即使我將x和y設置爲零,我也什麼也得不到。 – Eugene