Created
October 31, 2019 04:42
-
-
Save adityasonel/121435221b045697abce85a59fd069a1 to your computer and use it in GitHub Desktop.
Shadowed textview wrapper over default textview available in Android SDK.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ShadowTextView extends TextView { | |
public ShadowTextView(Context context, AttributeSet attrs) { | |
super(context, attrs); | |
final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.ShadowTextView); | |
final float shadowRadius; | |
final float shadowDx; | |
final float shadowDy; | |
final int shadowColor; | |
try { | |
final float shadowRadiusFromAttributes = attributes.getDimension(R.styleable.ShadowTextView_shadowRadius, 0f); | |
shadowRadius = shadowRadiusFrom(shadowRadiusFromAttributes); | |
shadowDx = attributes.getDimension(R.styleable.ShadowTextView_shadowDx, 0f); | |
shadowDy = attributes.getDimension(R.styleable.ShadowTextView_shadowDy, 0f); | |
shadowColor = attributes.getColor(R.styleable.ShadowTextView_shadowColor, 0); | |
} finally { | |
attributes.recycle(); | |
} | |
if (shadowColor != 0) { | |
setShadowLayer(shadowRadius, shadowDx, shadowDy, shadowColor); | |
} else { | |
getPaint().clearShadowLayer(); | |
} | |
} | |
private static float shadowRadiusFrom(float shadowRadiusFromAttributes) { | |
// App can crash on some devices if shadow radius is more than 25 pixels | |
// On Samsung Galaxy S6 this crash happens when you copy a text from an input field | |
// https://stackoverflow.com/questions/4866928/ranges-for-radius-in-shadowradius-and-visiblity-in-textview?lq=1 | |
final float radiusCapped = Math.min(shadowRadiusFromAttributes, 25f); | |
// Threat radius between 0 and 1 pixels as 1 pixel to prevent | |
// unexpected shadow loss on lower-dpi devices. | |
final float radius; | |
if (radiusCapped > 0f && radiusCapped < 1f) { | |
radius = 1f; | |
} else { | |
radius = radiusCapped; | |
} | |
return radius; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment