2012-12-02 2 views
0

캔버스에서 텍스트를 TextView 하위 클래스에 가운데 맞추려고합니다.캔버스에 텍스트를 가운데에 맞출 수 없습니다.

이클립스 : 그것은 장치에 이클립스에서 잘 보이는,하지만

enter image description here

장치 :

enter image description here

나는이 방법으로 텍스트를 중심하려는 이유가있다 . 나는이 문제에 속하지 않기 때문에 여기에서 설명하지도 않는다. (또한 코드에도 포함되지 않는다.)

이미 딥과 SP를 사용하고 있습니다.

코드 :

package com.example.test2; 

import android.content.Context; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.Paint; 
import android.graphics.Rect; 
import android.util.AttributeSet; 
import android.widget.TextView; 

public class CenterTest extends TextView { 
    private Paint paint; 
    private Paint paint2; 
    private Rect bounds; 

    public CenterTest(Context context) { 
     super(context); 
    } 

    public CenterTest(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     paint = new Paint(); 
     paint2 = new Paint(); 
     bounds = new Rect(); 
    } 

    public void draw(Canvas canvas) { 
     canvas.save(); 

     int width = getWidth(); 
     int height = getHeight(); 

     //draw background 
     paint2.setColor(Color.rgb(0, 0, 0)); 
     paint.setStyle(Paint.Style.FILL); 
     canvas.drawRect(0, 0, width, height, paint2); 

     //measure text 
     paint.setTextSize(getTextSize()); 
     paint.getTextBounds(getText().toString(), 0, getText().toString().length(), bounds); 
     int textWidth = bounds.width(); 
     int textHeight = bounds.height(); 

     //center before drawing text 
     canvas.translate((width/2) - (textWidth/2), 0); 
     canvas.translate(0, (height/2) - (textHeight/2)); 

     //let TextView.onDraw() do the rest 
     super.onDraw(canvas); 

     canvas.restore(); 
    } 
} 

XML :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#ffffff" 
    > 
    <com.example.test2.CenterTest 
     android:layout_width="100dip" 
     android:layout_height="30dip" 
     android:text="label" 
     android:textColor="#ffffff" 
     android:singleLine="true" 
     android:textSize="12sp" 
    /> 
</RelativeLayout> 

아마 이유는 TextView.onDraw (어딘가에)하지만 코드의 200 개 이상의 라인을 그리고 지금은 시간이 없어 ... 그리고 거기 있는지 확실하지 않습니다.

미리 감사드립니다.

답변

0

안드로이드를 사용하려고 : 중력 = "센터"를

<com.example.test2.CenterTest 
    android:layout_width="100dip" 
    android:layout_height="30dip" 
    android:text="label" 
    android:textColor="#ffffff" 
    android:singleLine="true" 
    android:textSize="12sp" 
    android:gravity="center" 
/> 
+1

아니, 나는 다른 방법을 중심으로하고 싶다고 말했다. – Ixx

관련 문제