2011-09-12 26 views
15

我需要爲android創建一個應用程序,其中雙色文本將顯示在雙色背景上。見左圖。然後,該行應該與動畫一起移動,並且結果圖像應該像在右邊的圖片上。如何顯示帶雙色背景的文字?

我有以下問題:

  1. 我應該使用一些2D引擎這樣做呢?或者,使用標準視圖可以嗎?怎麼做?
  2. 如何在圖片上繪製文字?

pic1 --------- pic2

+0

我可以高大你這,這不是簡單的任務,在所有。但很好的開始可能是使用一些自定義組件,如帆布 – Lukap

+0

有沒有任何功能,它可以恢復文本顏色取決於背景? –

+0

你有沒有想過如何實現這個?我可能會有一個答案,如果你沒有 – Ludevik

回答

1

這是不完整的答案,我只是給建議。 我知道一個可能的解決方案,你如何做左邊的圖片和右邊的圖片。但我無法想出的部分是動畫。我的意思是如果你想在狀態之間平滑的動畫。如果你只是想交換視圖很容易,只是看看fliper和它,但我不認爲你想要實現...

你可以做的事情之一是設置背景讓說320寬度,並說讓0-160白色和160-320黑色。然後

tv.setText(Html.fromHtml("<font color='black'>black on white</font> <font color='white'>white on black</font>")); 
當然

,你需要做的許多信件怎麼會黑,多少白精確的計算,但畢竟是概念

+0

我認爲有更簡單的解決方案 - 我需要繪製文本兩次 - 第一次使用白色,第二次使用黑色。但是我不應該爲此使用標準的TextViews。 –

+0

我只是建議你做一個方法,我相信有更精確的解決方案來做你想做的事情,這是我第一次想到 – Lukap

+0

你有沒有找到其他解決方案? – Lukap

13

的Android圖形API我會用夾子創建剪輯區域的路徑。 步驟:

  • 填充畫布黑色:

black canvas

  • 繪製你的白色文本在畫布上:

enter image description here

  • 創建剪輯路徑,並把它應用到你的畫布(見Canvas.clipPath(Path)
  • 用白色填充畫布:

enter image description here

  • 得出同樣的文本在步驟2中的黑色帆布:

enter image description here

3

您可以創建一個自定義視圖,使用PorterDuff篩選器來掩蓋文字。

這裏是如何可能看起來:

public class MaskedText extends View { 

    String sText; 
    Paint p, pReplace, pMask; 

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

     // base paint for you text 
     p = new Paint(Paint.ANTI_ALIAS_FLAG); 
     p.setTextSize(40); 
     p.setTextAlign(Paint.Align.CENTER); 
     p.setColor(0xFF000000); 
     p.setStyle(Paint.Style.FILL); 

     // replacement color you want for your the part of the text that is masked 
     pReplace = new Paint(p); 
     pReplace.setColor(0xFFFFFFFF); 
     pReplace.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OVER)); 

     // color of the drawing you want to mask with text 
     pMask = new Paint(); 
     pMask.setColor(0xFFFF0000); 
     pMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR)); 
    } 

    public void setText(String text) { 
     sText = text; 
    } 

    @Override 
    public void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 

     canvas.save(); 

     // here you draw the text with the base color. In your case black 
     canvas.drawText(sText, getWidth()/2, getHeight()/2, p); 

     // then draw the shape any graphics that you want on top of it 
     canvas.drawCircle(getWidth()/2, getHeight()/2, 50, pMask); 
     canvas.drawCircle(getWidth()/2 + 50, getHeight()/2 + 5, 20, pMask); 
     canvas.drawCircle(getWidth()/2 - 45, getHeight()/2 - 10, 30, pMask); 

     // finally redraw the text masking the graphics 
     canvas.drawText(sText, getWidth()/2, getHeight()/2, pReplace); 

     canvas.restore(); 
    } 
} 

這是結果: Masked text

相關問題