2016-07-13 5 views
2

Как я могу создать линейную компоновку в прозрачном градиентном фоне андроида, в макете в настоящее время есть размытое изображение в качестве фона, но мне нужно, чтобы размытое изображение было слегка прозрачным в верхней части макета и затем перейдите в непрозрачный снизу.Линейная схема Android с градиентным прозрачным фоном

Макет вложен в прокрутку parallax, чтобы макет мог скользить по верхней части изображения заголовка.

я произвожу размытые рисуют так:

final View content = img_header; 
    if (content.getWidth() > 0) { 
     Bitmap image = BlurBuilder.blur(content); 
     BitmapDrawable background = new BitmapDrawable(image); 

     ll_parent_layout.setBackground(background); 
    } else { 
     content.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
      @Override 
      public void onGlobalLayout() { 
       Bitmap image = BlurBuilder.blur(content); 
       BitmapDrawable background = new BitmapDrawable(image); 
       ll_parent_layout.setBackground(background); 
      } 
     }); 
    } 

размывание строитель выглядит следующим образом:

public class BlurBuilder { 
private static final float BITMAP_SCALE = 1f; 
private static final float BLUR_RADIUS = 25f; 

public static Bitmap blur(View v) { 
    return blur(v.getContext(), getScreenshot(v)); 
} 

public static Bitmap blur(Context ctx, Bitmap image) { 
    int width = Math.round(image.getWidth() * BITMAP_SCALE); 
    int height = Math.round(image.getHeight() * BITMAP_SCALE); 

    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false); 
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap); 
    /// compress bitmap here 

    RenderScript rs = RenderScript.create(ctx); 
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); 
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap); 
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap); 
    theIntrinsic.setRadius(BLUR_RADIUS); 
    theIntrinsic.setInput(tmpIn); 
    theIntrinsic.forEach(tmpOut); 
    tmpOut.copyTo(outputBitmap); 

    return outputBitmap; 
} 

public static Bitmap blur(Context ctx, Bitmap image, float scale, float radius) { 
    int width = Math.round(image.getWidth() * scale); 
    int height = Math.round(image.getHeight() * scale); 

    Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false); 
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap); 

    RenderScript rs = RenderScript.create(ctx); 
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs)); 
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap); 
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap); 
    theIntrinsic.setRadius(radius); 
    theIntrinsic.setInput(tmpIn); 
    theIntrinsic.forEach(tmpOut); 
    tmpOut.copyTo(outputBitmap); 

    return outputBitmap; 
} 


private static Bitmap getScreenshot(View v) { 
    Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888); 
    Canvas c = new Canvas(b); 
    v.draw(c); 
    return b; 
} 
} 
+0

Можете ли вы выслать вам код для удобства? –

+0

@ Сообщение KaranMer отредактировано по вашему запросу – MichaelStoddart

+0

Вы не используете ресурс drawable для этого? –

ответ

1

Поскольку вы манипулируете Bitmap, чтобы сгенерировать размытое изображение, вы можете использовать шейдер LinearGradient, чтобы добавить к нему прозрачность, как в this answer.

public Bitmap addGradient(Bitmap src) { 
    int w = src.getWidth(); 
    int h = src.getHeight(); 
    Bitmap overlay = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(overlay); 

    canvas.drawBitmap(src, 0, 0, null); 

    Paint paint = new Paint(); 
    LinearGradient shader = new LinearGradient(0, 0, 0, h, 0xFFFFFFFF, 0x00FFFFFF, Shader.TileMode.REPEAT); 
    paint.setShader(shader); 
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); 
    canvas.drawRect(0, h - h, w, h, paint); 

    return overlay; 
} 
+0

Работал как шарм, я искал решение для этого, по крайней мере, неделю! – MichaelStoddart

+0

У меня сейчас проблема с этим решением, кажется, что на фоне, где размытое изображение является черным, вы можете видеть линию, где начинается градиент, вы когда-нибудь имели эту проблему раньше? – MichaelStoddart

0

Вы можете использовать Drawable XML, чтобы установить градиент макет, как показано ниже.

Место под кодом в файле say mybg.xml и поместить его в папку с возможностью копирования.

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle" 
> 
    <gradient 
     android:startColor="@color/mycolor1" 
     android:endColor="@color/mycolor2" 
     android:angle="270" /> 
</shape> 

использование 8 голец хэш-код для цветов, так что ваши цвета могут быть как это

mycolor1 -> #000000aa //this will give you transparent colored background 
mycolor2 -> #ff00aa00 //this will be opaque like background 

первые два символа здесь установить уровень альфа для цвета.

0

может сделать это таким образом:

просто убедитесь, что Bitmap изменчиво, также используя значение fadingPortion (> = 0 и < = 1) можно сделать только часть фонового градиента прозрачного

public static Bitmap makeBitmapTransparent(Bitmap mutableBitmap, float fadingPortion) { 
    final Shader gradientShader = new LinearGradient(
      mutableBitmap.getWidth()/2, 0, 
      mutableBitmap.getWidth()/2, mutableBitmap.getHeight() * fadingPortion, 
      0x00000000, 0xFF000000, 
      Shader.TileMode.CLAMP); 

    Paint paint = new Paint(); 
    paint.setShader(gradientShader); 
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); 

    Canvas canvas = new Canvas(mutableBitmap); 
    canvas.drawRect(new Rect(0, 0, mutableBitmap.getWidth(), (int) (mutableBitmap.getHeight() * FADING_PORTION)), paint); 
    canvas.drawBitmap(mutableBitmap, 0, 0, null); 

    return mutableBitmap; 
} 
+0

Что я могу пройти в качестве затухающей части? – MichaelStoddart

+0

поплавок в диапазоне от 0 до 1. 0,25 (например) означает, что только верхняя четверть будет градиентно прозрачной – Sharpe