Ed Lee
Ed Lee

Reputation: 187

Am I applying the colorfilter in the right place in my custom ImageView?

I'm fairly new to creating my own custom views and onDraw() always strikes me as a scary place so I wanted to make sure I'm applying the color filter in the right place:

public class ColorImageView extends ImageView {

  private int mColor = -1;

  public ColorImageView(Context context) {
    super(context);
  }
  public ColorImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ColorImageView);
    mColor = ta.getColor(R.styleable.ColorImageView_customColor, -1);
    ta.recycle();
  }

  @Override
  protected void onDraw(Canvas canvas) {
    if (mColor != -1) {
      Util.applyColorFilter(getDrawable(), mColor);
    }
    super.onDraw(canvas);
  }
}

Upvotes: 0

Views: 48

Answers (2)

Nikola Despotoski
Nikola Despotoski

Reputation: 50548

onDraw() is not a place where you should perform heavy calculation. onDraw() will be called as many times as your view changes, every time it changes it will need to redraw itself and onDraw() called.

Move your color filtering inside setImageDrawable() after the super call. This method ensures that drawable will be drawn to the canvas and you can apply your color filter. setImageDrawable ensures that the ImageView will be invalidate once.

@Override
public void setImageDrawable(@NotNull drawable){
 super.setImageDrawable(drawable);
 applyColorFilter();
}

The best solution may be to call the applyColorFilter from both the constructor and this setImageDrawable().

Upvotes: 1

Gabe Sechan
Gabe Sechan

Reputation: 93614

That will work, but it would make more sense to apply it only when mColor is changed, and keep it set. That way you don't need to continually reapply the filter each onDraw call, which is going to hit performance.

Upvotes: 0

Related Questions