Press ESC to close

Xamarin Forms Adjusting Odds in Pictures

Hello friends. In this article, after taking a photo from a server with Xamarin Forms, we will adjust the aspect ratio. This process is sometimes very important to us. I had this problem in ListView. The lengths of the pictures I show in ListView were different. Accordingly, we had to adjust the length of the picture without any space around the edges.

We need to show the pictures we will show first in the FFCacheImage package. Since the photos are usually from Url, we will take advantage of this View’s Success function. The reason we use this function is to get the width and height information of the picture after we take the photo from the url.

First we need to take the width of the screen. Thus, we will be able to adjust the length of the picture according to the width of the screen. There is an override function on each page to take the width of the screen. I take the width of the screen with the OnSizeAllocated function and throw it into the variables I create in the page.

protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            screenHeight = height;
            screenWidth = width;
        }

Then I add the Success method. If I have a blank screen on the screen first, I find the width of the picture in Url by removing the margins from the width of the screen. Then I find the original ratio of the picture. I can find the original width divided by height to find the ratio. After that, I remove the margins from the width of the screen and divide the width I find with the original ratio, so I find a height relative to the screen.

private void CachedImage_Success(object sender, CachedImageEvents.SuccessEventArgs e)
        {
            if (screenWidth != -1 && screenHeight != -1)
            {
                for (int i = 0; i < announcements.Data.Count; i++)
                {
                    if (announcements.Data[i].ImageUrl == e.ImageInformation.Path)
                    {
                        announcements.Data[i].Width = screenWidth - 20;
                        var ratio = e.ImageInformation.OriginalWidth / (screenWidth - 20);
                        announcements.Data[i].Height = e.ImageInformation.OriginalHeight / ratio;
                        if (e.LoadingResult != FFImageLoading.Work.LoadingResult.MemoryCache)
                        {
                            listViewAnnouncements.ItemHeightChanged(i);
                        }
                    }
                }
            }
        }

After that, I tell the FFCacheImage control that we put in the ListView and your size has changed.

If you have questions, you can reach them by sending comments or e-mails. Good work.

Leave a Reply

Your email address will not be published. Required fields are marked *