2013-06-25 35 views
0

我已經設法創建繪畫,創建一個非常漂亮的平滑筆劃圍繞文本。但是我在繪製到需要的地方時遇到了麻煩,主要是我相信擴展視圖而不是TextView的事實?Android - 筆觸文字,延伸textview/view

我的目標是能夠圍繞我想要的佈局上的任何文本進行筆劃。

DrawView.java

public class DrawView extends View{ 
     Paint paint = new Paint(); 
     String text = "Blank"; 

     public DrawView(Context context, AttributeSet attrs, int defStyle) { 
      super(context, attrs, defStyle); 

     } 

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


    } 

    public DrawView(Context context) { 

     super(context); 

    } 



    public void setText(String text) { 
     this.text = text; 
    } 




    public String getText() { 
     return text; 
    } 

    public void draw(Canvas canvas) { 

     Paint strokePaint = new Paint(); 
     strokePaint.setARGB(255, 0, 0, 0); 
     strokePaint.setTextSize(28); 
     //strokePaint.setTypeface(tf); 
     strokePaint.setStyle(Paint.Style.STROKE); 
     strokePaint.setStrokeJoin(Paint.Join.ROUND); 
     strokePaint.setStrokeCap(Paint.Cap.ROUND); 
     strokePaint.setStrokeWidth(9); 
     strokePaint.setAntiAlias(true); 


     Paint textPaint = new Paint(); 
     textPaint.setARGB(255, 255, 255, 255); 
     textPaint.setTextSize(28); 
     //textPaint.setTypeface(tf); 
     textPaint.setAntiAlias(true); 

     canvas.drawText(text, 99, 99, strokePaint); 
     canvas.drawText(text, 99, 101, strokePaint); 
     canvas.drawText(text, 101, 99, strokePaint); 
     canvas.drawText(text, 101, 101, strokePaint); 
     canvas.drawText(text, 100, 100, textPaint); 

     super.draw(canvas); 
    } 

} 

XML

<com.shadow.pets.DrawView 
     android:id="@+id/energyText" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     /> 

這種觀點將覆蓋我的整個的LinearLayout,我有過它不消耗控制?如果我擴展TextView,我無法讓它工作!

對不起,如果它令人困惑,我知道我必須離開軌道,但一直在努力幾個小時,找不到更清楚的話!

回答

1

我認爲現在的問題是,您的DrawView不會「知道」它有多大,所以Wrap_content只佔用所有可用空間。你可以通過覆蓋onMeasure()來解決這個問題。你可能想要像這樣包裝成文字的大小:

@Override 
protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec){ 
    super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
    int padding = 10; 
    Rect r = new Rect(); 
    Paint p = new Paint();; 
    p.setTextSize(28); 
    p.getTextBounds(text, 0, text.length(), r); 
    this.setMeasuredDimension(r.right - r.left + padding, 
     r.bottom - r.top + padding); 
} 

「填充」是爲筆畫邊框添加額外的大小。然後在你的畫類,改變你的drawTexts看起來像這樣:

int padding = 5; 
int x = this.getLeft() + padding; 
int y = this.getBottom() - padding; 
canvas.drawText(text, x - 1, y - 1, strokePaint); 
canvas.drawText(text, x - 1, y + 1, strokePaint); 
canvas.drawText(text, x + 1, y - 1, strokePaint); 
canvas.drawText(text, x + 1, y + 1, strokePaint); 
canvas.drawText(text, x, y, textPaint); 

這應該工作,在理論上。當我嘗試它時,只要DrawView是LinearLayout中最左邊的視圖,它看起來很棒,但當有TextView和DrawView時,它被部分覆蓋。我不知道爲什麼:(但我希望這可以幫助你開始!

+0

完美!謝謝! – Jonno