Search code examples
xamarinandroid-imageviewandroid-imagexamarin.forms

Xamarin Forms Resize Image inside Listview


How can I set the size of the image inside of a list view. Currently I have several lists that have icons but I don't see any options for changing the aspect ratio or size of the image so it just gets blown up to the height of the list item.

all the images are from the Drawable folder

        var cell = new DataTemplate(typeof(MenuTextCell));
        cell.SetBinding(TextCell.TextProperty, "Title");
        cell.SetBinding(ImageCell.ImageSourceProperty, "IconSource");
        cell.SetValue(BackgroundColorProperty, Color.Transparent);
        cell.SetValue(TextCell.TextColorProperty, Color.FromHex("262626"));

I am using a custom renderer

public class MenuTextCellRenderer : ImageCellRenderer
    {
        protected override View GetCellCore (Cell item, View convertView, ViewGroup parent, Context context)
        {
            var cell = (LinearLayout)base.GetCellCore (item, convertView, parent, context);
            cell.SetPadding(20, 10, 0, 10);
            cell.DividerPadding = 50;

            var div = new ShapeDrawable();
            div.SetIntrinsicHeight(1);
            div.Paint.Set(new Paint { Color = Color.FromHex("b7b7b7").ToAndroid() });

            if (parent is ListView)
            {
                ((ListView)parent).Divider = div;
                ((ListView)parent).DividerHeight = 1;
            }

            var icon = (ImageView)cell.GetChildAt(0);

            var label = (TextView)((LinearLayout)cell.GetChildAt(1)).GetChildAt(0);
            label.SetTextColor(Color.FromHex("262626").ToAndroid());
            label.TextSize = Font.SystemFontOfSize(NamedSize.Large).ToScaledPixel();
            label.TextAlignment = TextAlignment.Center;
            label.Text = label.Text.ToUpper();

            var secondaryLabel = (TextView)((LinearLayout)cell.GetChildAt(1)).GetChildAt(1);
            secondaryLabel.SetTextColor(Color.FromHex("262626").ToAndroid());
            secondaryLabel.TextSize = Font.SystemFontOfSize(NamedSize.Large).ToScaledPixel();
            label.TextAlignment = TextAlignment.Center;


            return cell;
        }

Solution

  • You are now dealing with an Android ImageView.

    You have your reference via var icon = (ImageView)cell.GetChildAt(0).

    You can now customize it via methods such as .setScaleType() for aspect ratio related, and use .layout() to change the position / size.