Display colors in percentage

Asked

Viewed 77 times

3

I’m trying to make an app to take a photo, display in imageview and extract colors with the Palette library. All of this I’ve done.
What I need is to display the result (Population) in percentage of the total and not in number of pixels. Someone could give a help?
Thanks in advance.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if( convertView == null ) {
        holder = new ViewHolder();
        convertView = LayoutInflater.from( getContext() ).inflate( R.layout.color_item, parent, false );
        holder.view = (TextView) convertView.findViewById( R.id.view );
        convertView.setTag( holder );
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.view.setBackgroundColor(getItem(position).getRgb());
    holder.view.setTextColor(getItem(position).getBodyTextColor());
    holder.view.setText("Population: " + getItem(position).getPopulation());

    return convertView;
}

1 answer

2

For this you should know the total Pixels that the image has!

For this do as follows:

int totalPxls = 0;
for(Palette.Swatch swatch : palette.getSwatches())
{
    totalPxls += swatch.getPopulation();
}

With this value, we can apply the rule of 3 to know the percentage:

Double porcentagem = ((getItem(position).getPopulation()*100.0D)/totalPxls);

So you can carry the totalPxls of your Activity to the Adapter:

public class SwatchAdapter extends ArrayAdapter {
    private Integer totalPixels;
    public SwatchAdapter(Context context, int resource, Integer totalPixels) {
        super(context, resource);
        this.totalPixels = totalPixels;
    }
}
  • Thiago, thank you for your attention, but I can’t. I have 2 Mainactivity classes where I already have that loop you suggested, I just added the Pixel count, but I can’t calculate the % because I don’t have the position of the items there yet and in the Swatchadapter class, for my ignorance, I cannot get the totalPxls calculated in Mainactivity.

  • Add one more parameter in your Swachtadapter constructor. Total pixels. And in the class add one more property. So you can use it in your method

  • Sorry Thiago but don’t know "add another property in class"

  • No need to apologize! We’re here to help you! I’m on my way home. When I get there I’ll edit the answer and explain it to you !

  • I edited! try to implement, and any questions, post here!

  • I got Thiago. I changed a little but his help was essential. Now I can continue my project. I actually abandoned the loop because I was hoarding the totalPxls. I will try to edit and post my Swatchadapter class because it might be useful to someone.

  • I can’t edit......

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.