Add shadow to view android

Take control of view’s shadow — Android

You can find updated code that is written in Kotlin here

Apr 23, 2017 · 4 min read

Let’s say you’re looking for how to implement shadow on your View in Android and you are going to Google something. You will probably find these 3 answers.

We are going to check these answers, and after we check them all I will suggest new way that you can implement shadow in any View you want.

Use drawable with multi different color solid (worse thing that you can do)

Just use 5–6 shapes that have padding, and at the end the shape that will be your view’s main background, those shapes will be overlapping on each other and Baam! you have drop shadow

Let’s see t he result. Yes for some people this one is acceptable (not for me), but let’s enable Debug GPU Overdraw and check result too

4x+ Overdraw it’s not good, so never ever ever ever use this solution, not worth it.

Android elevation (supported from API 21)

It’s easy to use, just add one attribute to your view’s XML or even enable it with Java code in your View class check Android documentation

The result is perfect, overdraw is acceptable but you older APIs will not support this shadow

Let’s check overdraw and the result.

Do you see that green border on left|top|right of overdraw result that means some part of view overdraw 2x time I have no idea why this is happening.

CardView

When you are using CardView you will see shadow in all APIs, but the result in older APIs are not same as 21+ APIs

Cardview overdraw is exactly same as elevation

But there is one thing you should know; if you go to CardView source code you will notice that CardView extends from FrameLayout (link), That means if you want to use LinearLayout as Parent View it will add inside of Framelayout, so you will always have one more extra overdraw in your views. And when you are using CardView (Elevation) you can not change the shadow’s color, you can not change the shadow’s direction (top|left, bottom|right) you need to follow material design in your application.

Читайте также:  Планшет андроид не видит свою память

Using Shape Drawable (New way to implement shadow)

Why not create the shadow ourself? You need to create a custom view and initial in background.

First, let’s see the result.

The result is same as CardView, we don’t have that green 2x overdraw and you can use it in any view you want and you can control your shadow’s direction and color.

Here is just a simple example how it works.

You can add this view in your XML and you have LinearLayout that support rounded box with drop shadow.

You can create your own attribute and pass background color, corner radius, shadow color through XML too.

And the good part is you are not forced to use FrameLayout as your parent view, you can easily create any view you want.

Let’s go to ViewUtils class and see magical things.

This function generate shadow with 3 different direction with custom radius and color.

First, we create background paint to draw our background color and we will add shadow layer with only corner radius that we want.

Next, we add padding to shape drawable to prevent overlapping view’s content on the shadow layer.

With ‘setShadowLayer’ you can change the color of shadow and also the direction of shadow and after that, you need to add a corner to your shadow layer too.

And at the end we merge it to LayerDrawable and set Inset to drawable for not seeing cutting shadow, that’s all.

It’s just simple example,you can use more that one ShapeDrawable to create customizable shadow.

In the next post, I will show how you can clip shape in view with shadow background.

Источник

Mastering Shadows in Android

Jan 9, 2018 · 6 min read

If we want to create better apps, I believe that we need to follow material design guideline.In general terms, Material design is a three-dimensional environment containing light, material, and cast shadows. Light and Shadow are important for us if we want to follow material design guideline in our application development process.

I will try to explain following topics in this article.

  • 3D in Android
  • Depth
  • Z value, elevation and Translation Z
  • Light
  • Button state (Pressed and Resting)
  • Outline
  • Custom Outline with ViewOutlineProvider

Before deep dive into shadow and light, I want to show you what our environment is.

What is 3D?

The material environmen t is a 3D space, which means all objects have x, y, and z dimensions. The z-axis is perpendicularly aligned to the plane of the display, with the positive z-axis extending towards the viewer. In Material Design world, every object has 1 dp thickness.

Читайте также:  Android google accounts apk

What is Depth in Android?

Material design differs from other design guides because It has depth. We can say that depth defines view’s importance level in user interface. We can think there is a paper layer in our desk. If we put another paper on it, our eyes will perceive that it has a depth.

Let’s imagine it with an app screenshot from the material design guideline.

Let’s see our elements in the screen.

  • Screen (Surface layer — 0 depth)
  • Cardviews
  • Appbar Layout
  • Floating Action Button

Every element has a priority to another. Cardviews can scroll in its recyclerview. So we can say that our first layer is scrollable content. The second layer is appbar layout. The third layer (Top layer) is the floating action button.

So how do we define the order? How do we make the user feel the depth? Answer: Z- value.

What is Z-value in Android?

The Z value for a view has two components:

  • Elevation: The static component.
  • Translation Z: The dynamic component used for animations.

I always wonder that what is the difference between elevation and translation.

Elevation is static. So you don’t change it dynamically. If you want to animate your view in Z-axis (like pressing and resting) you need to use translation-Z attribute.

Translation Z is dynamic. In your empty project, If you create a button and press it, you will see that shadow gets bigger with an animation. Actually, elevation value is not changing. Translation Z property is changing. Android is using default state list animator changes translation Z property of the view.

Z-Value = Elevation + TranslationZ

What if we change the value of Z of two views that intersect. Does Android handle the order on the screen? Yes. Let me show you that with a diagram that I designed.

Источник

Урок 4. Android Material Design. Установка теней и обрезка View

Перевод документации официального сайта developer.android.com

Рисунок 1. Тени для различных высот view.

Чтобы установить высоту view в макете используйте атрибут android:elevation. Чтобы установить высоту в коде activity, используйте метод View.setElevation().

Чтобы установить смещение, используйте метод View.setTranslationZ().

Новые методы ViewPropertyAnimator.z() и ViewPropertyAnimator.translationZ() позволяют легко анимировать высоту view. Для получения дополнительной информации, смотрите справку по ViewPropertyAnimator и руководство разработчика о свойствах анимации.

Вы так же можете использовать StateListAnimator чтобы установить анимации декларативно. Это особенно полезно в тех случаях, когда изменяется состояние триггера анимации, например, когда пользователь нажимает на кнопку. Для получения дополнительной информации, смотрите Изменение состояния анимации view.

Значение Z измеряется в dp (density-independent pixels).

Настройте тени и контуры

Границы фона drawable view определяют форму его тени. Контуры представляют собой внешнюю форму графического объекта и определяют область для сенсорного отклика.

Рассмотрим view, определенное с помощью фона dravable:

Читайте также:  Android fill parent and wrap content

Фон drawable определен как прямоугольник с закругленными углами:

View отбрасывает тень с закругленными углами, после того как фон drawable установил границы view. Создание пользовательского контура переопределяет форму тени view по умолчанию.

Чтобы установить пользовательский контур для view в коде:

1. Унаследуйтесь от класса ViewOutlineProvider.
2. Переопределите метод getOutline().
3. Назначьте нового поставщика контура для вашего view с помощью метода View.setOutlineProvider() .

Вы можете создать овальные и прямоугольные очертания с закругленными углами используя методы класса Outlines. Поставщик контура для view по умолчанию получает контур из фона view. Чтобы view не отбрасывала тень, установите значение поставщика контура в null.

Обрежьте view

Обрезание позволяет вам легко изменить форму view. Вы можете обрезать view для совместимости с другими элементами дизайна или изменить форму view в ответ на действия пользователя. Вы можете обрезать view к его области контура с помощью метода View.setClipToOutline() или используя атрибут android:clipToOutline. Только прямоугольник, круг и скругленный прямоугольник поддерживают обрезание, как определено в методе Outline.canClip().

Чтобы обрезать view в форме drawable, установите drawable в качестве фона view (как показано выше), и вызовите метод View.setClipToOutline().

Обрезание view это дорогостоящая операция, поэтому не анимируйте форму, которую вы используете чтобы обрезать view. Для достижения этого эффекта используйте Reveal эффект анимации.

Источник

Add shadow to view android

This library draw android view shadow by ShadowLayer. You may don’t like the CardView’s black shadow which we can’t change it’s color. Same to CardView wrap content and set shadow radius. You can change shadow color, foreground color and corner radius everywhere. Because the shadow is draw in the view. So you must add space to draw the shadow. The ShadowView add one param shadowMargin which must be set before you add shadow radius to the view.

Caveat: Margin In UI

= layout_margin + shadow_margin(Add by ShadowView)

H H H
Change Radius Change foreground Change Corners
Change shadow color Change shadow margin Demo

About

Android custom shadow view, can replace your CardView

Источник

Add shadow to view android

This library draw android view shadow by ShadowLayer. You may don’t like the CardView’s black shadow which we can’t change it’s color. Same to CardView wrap content and set shadow radius. You can change shadow color, foreground color and corner radius everywhere. Because the shadow is draw in the view. So you must add space to draw the shadow. The ShadowView add one param shadowMargin which must be set before you add shadow radius to the view.

Caveat: Margin In UI

= layout_margin + shadow_margin(Add by ShadowView)

H H H
Change Radius Change foreground Change Corners
Change shadow color Change shadow margin Demo

About

Deprecated because of the performance not fine. Android custom shadow view, can replace your CardView

Источник

Оцените статью