0

からクラスを拡張し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);}
4

2 に答える 2

2

コードを実行したところ、すぐにLintエラーが発生しました。init()あなたはあなたをに設定しmTextPaintていますandroid.R.color.blackintこれは静的な値であるため、その変数の実際の値はであることがすぐにわかりました。0x0106000cこれはほぼ完全に透過的です。getResources().getColor(android.R.color.black)またはプレーンol'を使用する必要がありますColor.BLACK

textSize12のaは非常に小さいことに注意してください。このコードは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します。画面に表示されます。

于 2012-12-20T14:19:41.400 に答える
-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="..."
    />
于 2012-12-20T13:54:08.533 に答える