android – display colors in percentage

Question:

I'm trying to make an app to take a photo, display in imageview and extract the colors with the Palette library. All this I have already done.
What I need is to display the result (Population) as a percentage of the total and not as a number of pixels. Could anyone help?
Thank you very much 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;
}

Answer:

For this you must know the total number of pixels the image has!

To do 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 that you can transport 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;
    }
}
Scroll to Top