2014-01-14 198 views
1

我想以編程方式呈現TextView的邊緣褪色。通過哪種模式,我可以創建一個真正的alpha梯度?PorterDuff.Mode等效於邊緣褪色

一個真正的邊緣衰落應順利地從1.0減少透明度(沒有覆蓋梯度劈)至0.0使得頂視圖淡出到背景圖。

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

    int y = 0; 
    int height = 300; 
    int width = getWidth(); 

    LinearGradient shader = new LinearGradient(width/2, y, width/2, y + height, 0xff000000, 0x0000000, Shader.TileMode.CLAMP); 

    Paint p = new Paint(); 
    p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.XXX)); // Which mode works? 
    p.setShader(shader); 

    canvas.drawRect(0, y, width, y + height, p); 
} 

我試過所有的組合,他們都沒有工作?這是不可能的嗎?

+0

你有定期無效'TextView'? –

+0

@鄭紅旺,問題是我無法獲得所需的邊緣衰落結果。我嘗試了所有的'PorterDuff.Mode'選項,它只畫黑到透明漸變。我想讓文本的不透明度像佈局'requireFadingEdge'屬性一樣淡化爲零。 –

+0

'PorterDuff'用於在android官方演示中重疊兩個圖像。我認爲'動畫'可以爲你做到這一點。 –

回答

0

這是我用ImageView的解決方案。 我使用GradientDrawable作爲alpha。

活動:

@Override 
protected void onCreate (Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    getWindow().setBackgroundDrawableResource(R.drawable.background); 
    GradientImageView giv = new GradientImageView(this); 
    giv.setImageResource(R.drawable.bttf); 
    giv.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    setContentView(giv); 

} 


class GradientImageView extends ImageView 
{ 
    Drawable mDrawableMask; 
    Paint mPaintMask; 
    Bitmap mOriginal, mBitmapMask; 
    Canvas mCanvasOriginal, mCanvasMask; 


    public GradientImageView (final Context context) 
    { 
     super(context); 
     if (android.os.Build.VERSION.SDK_INT >= 11) 
      setLayerType(View.LAYER_TYPE_SOFTWARE, null); 

     mDrawableMask = getResources().getDrawable(R.drawable.gradient); 
     mPaintMask = new Paint(); 
     mPaintMask.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT)); 
    } 

    protected void setMask (Drawable mask) 
    { 
     mDrawableMask = mask; 
     mBitmapMask = null; 

    } 

    @Override 
    protected void onDraw (final Canvas canvas) 
    { 
     if (mOriginal == null) 
     { 
      mOriginal = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); 
      mCanvasOriginal = new Canvas(mOriginal); 
     } 

     super.onDraw(mCanvasOriginal); 


     if (mBitmapMask == null) 
     { 
      mBitmapMask = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888); 
      mCanvasMask = new Canvas(mBitmapMask); 
      mDrawableMask.setBounds(0, 0, getWidth(), getHeight()); 
      mDrawableMask.draw(mCanvasMask); 
     } 

     canvas.drawBitmap(mOriginal, 0, 0, null); 
     canvas.drawBitmap(mBitmapMask, 0, 0, mPaintMask); 
    } 
} 

gradient.xml

<?xml version="1.0" encoding="utf-8"?> 

<gradient 
    android:angle="-90" 
    android:centerColor="@android:color/transparent" 
    android:centerY="0.5" 
    android:endColor="@android:color/black" 
    android:startColor="@android:color/transparent" /> 

values.xml

<drawable name="background">#FF0000</drawable> 

結果(活動背景爲紅色) Yeah !