2012-12-20 17 views
0

我從ImageView擴展了課程,並且希望繪製一些文本。這不起作用,你知道爲什麼嗎?謝謝。在ImageView上繪製文本不起作用

@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; // 6 is half of the text size 
    canvas.drawText("your text", x, y, mTextPaint); 
} 

private void init(Context context, AttributeSet attrs, int defStyle) { 
    mTextPaint = new Paint(); 
    mTextPaint.setColor(android.R.color.black); 
    mTextPaint.setTextSize(12); 
    mTextPaint.setTextAlign(Paint.Align.LEFT);} 
+0

我懷疑它與dp和像素有關,因爲'setTextSize'在dp中,'imgWidth','imgHeight'以像素爲單位。並記錄'imgWidth'和'imgHeight'的值。 – stealthjong

+0

即使我將x和y設置爲零,我也什麼也得不到。 – Eugene

回答

2

我跑你的代碼,並立即得到了Lint錯誤。在init()中,您將mTextPaint設置爲android.R.color.black。因爲它是一個靜態值,我可以立即看到該變量的實際值int0x0106000c,這是幾乎完全透明的。你應該使用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

+0

這並沒有幫助 – Eugene

+0

@siik你的自定義視圖的尺寸是多少? – stealthjong

+0

現在我設置了mTextPaint.setTextAlign(Paint.Align.LEFT); canvas.drawText(「12」,0,0,mTextPaint);仍然沒有 – Eugene

-1

您應該能夠在不創建自己的類的情況下完成願望效果。只需使用可繪製的圖像設置TextView的背景即可。在演講泡泡中查看我的示例。

<TextView 
    android:id="@+id/textOverImage" 
    android:background="@drawable/speech_bubble" 
    android:text="@string/hello_world" 
    android:gravity="center" 
    android:layout_width="..." 
    android:layout_height="..." 
    />