绘制透明梯度alpha透明度从0到1(Draw transparent gradient with

2019-07-17 21:19发布

我在Android的动态生成的位图,我想从顶缘羽化,使得边界区域将是在顶部完全透明的,稍低于逐渐改变为完全不透明。

创建一个均匀的全透明的顶部边缘

transparentPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
transparentPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
Shader shader = new LinearGradient(0, 0, 0, 20,
                    Color.TRANSPARENT, Color.TRANSPARENT, Shader.TileMode.CLAMP);
transparentPaint.setShader(shader);
// the bitmap is dynamically generated beforehand
Canvas c = new Canvas(bitmap);
c.drawRect(0, 0, bitmapWidth, 20, transparentPaint);

阿尔法梯度,而不是完全透明的孔?

你将如何实现这样的事情:

[只是在这种情况下,顶部边缘]

Answer 1:

看看这个例子: 让位图上的触摸透明的某些区域

这是一种方式的渐变烤漆做到这一点:

Paint framePaint = new Paint();
for(int i = 1; i < 5; i++){
   setFramePaint(framePaint, i, imageW, imageH);
   myCanvas.drawPaint(framePaint);
}

...

private void setFramePaint(Paint p, int side, float iw, float ih){
                // paint, side of rect, image width, image height

                p.setShader(null);
                p.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

                float borderSize = 0.1f; //relative size of border
                //use the smaller image size to calculate the actual border size
                float bSize = (iw > ih)? ih * borderSize: ih * borderSize; 
                float g1x = 0;
                float g1y = 0;
                float g2x = 0;
                float g2y = 0;
                int c1 = 0, c2 = 0;

                if (side == 1){
                    //left
                    g1x = 0;
                    g1y = ih/2;
                    g2x = bSize;
                    g2y = ih/2;
                    c1 = Color.TRANSPARENT;
                    c2 = Color.BLACK;

                }else if(side == 2){
                    //top
                    g1x = iw/2;
                    g1y = 0;
                    g2x = iw/2;
                    g2y = bSize;
                    c1 = Color.TRANSPARENT;
                    c2 = Color.BLACK;


                }else if(side == 3){
                    //right
                    g1x = iw;
                    g1y = ih/2;
                    g2x = iw - bSize;
                    g2y = ih/2;
                    c1 = Color.TRANSPARENT;
                    c2 = Color.BLACK;


                }else if(side == 4){
                    //bottom
                    g1x = iw/2;
                    g1y = ih;
                    g2x = iw/2;
                    g2y = ih - bSize;
                    c1 = Color.TRANSPARENT;
                    c2 = Color.BLACK;
                }

                p.setShader(new LinearGradient(g1x, g1y, g2x, g2y, c1, c2, Shader.TileMode.CLAMP));

            }


Answer 2:

如果你能接受白边的,而不是透明的,尽量屏幕模式。 在PorterDuff.Mode.SCREEN模式,白色像素保持白色和黑色像素变为不可见。 创建一个覆盖位图,其中边缘为白色变为黑色,中间和你的图像混合的。 这将创建一个白边衰减到中间的照片的位图。



Answer 3:

罗曼盖伊使用非常相似的衰落,以你想要达到的目标,只有他还补充圆角除了这种效果



文章来源: Draw transparent gradient with alpha transparency from 0 to 1