Is there any way to apply vertical/horizontal fading edges to an ImageView
component?
I already tried android:fadingEdge
but unfortunately this attribute is deprecated and will be ignored as of API level 14, Any ideas?
I create the following extend of ImageView
to incorporate it with horizontal fading, you can easily change this class and add vertical fading. (Tested with the latest android version 4.4.2)
Base class:
public class FadingImageView extends ImageView {
private FadeSide mFadeSide;
private Context c;
public enum FadeSide {
RIGHT_SIDE, LEFT_SIDE
}
public FadingImageView(Context c, AttributeSet attrs, int defStyle) {
super(c, attrs, defStyle);
this.c = c;
init();
}
public FadingImageView(Context c, AttributeSet attrs) {
super(c, attrs);
this.c = c;
init();
}
public FadingImageView(Context c) {
super(c);
this.c = c;
init();
}
private void init() {
// Enable horizontal fading
this.setHorizontalFadingEdgeEnabled(true);
// Apply default fading length
this.setEdgeLength(14);
// Apply default side
this.setFadeDirection(FadeSide.RIGHT_SIDE);
}
public void setFadeDirection(FadeSide side) {
this.mFadeSide = side;
}
public void setEdgeLength(int length) {
this.setFadingEdgeLength(getPixels(length));
}
@Override
protected float getLeftFadingEdgeStrength() {
return mFadeSide.equals(FadeSide.LEFT_SIDE) ? 1.0f : 0.0f;
}
@Override
protected float getRightFadingEdgeStrength() {
return mFadeSide.equals(FadeSide.RIGHT_SIDE) ? 1.0f : 0.0f;
}
@Override
public boolean hasOverlappingRendering() {
return true;
}
@Override
public boolean onSetAlpha(int alpha) {
return false;
}
private int getPixels(int dipValue) {
Resources r = c.getResources();
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
dipValue, r.getDisplayMetrics());
}
}
Usage:
- Create the following object in your XML:
<com.your.package.FadingImageView
android:id="@+id/fade_image_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/some_drawable" />
- Then apply your desired fade side:
FadingImageView mFadingImageView = (FadingImageView) findViewById(R.id.fade_image_view);
mFadingImageView.setEdgeLength(28);
mFadingImageView.setFadeDirection(FadeSide.RIGHT_SIDE);