PorterDuff.Mode等效于边缘衰落

时间:2014-01-14 08:30:44

标签: android android-view porter-duff

我希望以编程方式渲染TextView的边缘淡入淡出。我可以通过哪种模式创建一个真正的alpha渐变?

真正的边缘渐变应该可以平滑地降低从1.00.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);
}

我尝试了所有的组合,但没有一个有效吗?这样做不可能吗?

1 个答案:

答案 0 :(得分: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 !