简体   繁体   English

Xamarin Forms 调整图像宽度以填充 stacklayout 而不进行顶部和底部剪切

[英]Xamarin Forms Resize image width to fill stacklayout without top and bottom clipping

This is the current code I have:这是我拥有的当前代码:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="WPapp.Views.Post">
    <ContentPage.Content>
        <ScrollView>
            <StackLayout Margin="10"
                         HorizontalOptions="Center"
                         VerticalOptions="FillAndExpand"
                         x:Name="PostContainer">
                <Image x:Name="FeaturedImage"
                       HorizontalOptions="Center"/>
                <Label x:Name="Title"
                       FontSize="Title"
                       FontAttributes="Bold"
                       Margin="0, 20, 0, 10"/>
                <Label x:Name="PostMeta"
                       FontSize="Caption"
                       FontAttributes="None"
                       Margin="0, 0, 0, 0"/>
            </StackLayout>
        </ScrollView>
    </ContentPage.Content>
</ContentPage>

Image image = new Image();
image.Source = imageSource;
image.Aspect = Aspect.AspectFill;
PostContainer.Children.Add(image);

This is the image:这是图像:

图片

This is the result:这是结果:

结果

The image is being filled horizontally as intended.图像正在按预期水平填充。

The problem is, the image is being clipped vertically.问题是,图像被垂直裁剪。 How can I prevent the image from being clipped and how do I display the full image without stretching?如何防止图像被剪裁以及如何在不拉伸的情况下显示完整图像?


As shown in the answer below, in order to resize the image so the width matches the maximum width of the StackLayout Container without clipping, I needed to set the HeightRequest of the image.如下面的答案所示,为了调整图像的大小,使宽度与 StackLayout Container 的最大宽度匹配而不进行裁剪,我需要设置图像的 HeightRequest。

I am retrieving posts from a WordPress Website.我正在从 WordPress 网站检索帖子。 To parse the JSON response from the Wordpress REST API, I am using the WordpressPCL package. To parse the JSON response from the Wordpress REST API, I am using the WordpressPCL package. In order to parse the HTML output that I get from the WordpressPCL get post content by ID method, I am using the HTML Agility Pack.为了解析我从 WordpressPCL 获得的 HTML output 通过 ID 方法获取帖子内容,我正在使用 HTML 敏捷包。

With the HTML Agility Pack, I was able to get the Wordpress media ID, this ID was then used to query the Wordpress API and get the original image's width and height and caption text with the WordpressPCL package. With the HTML Agility Pack, I was able to get the Wordpress media ID, this ID was then used to query the Wordpress API and get the original image's width and height and caption text with the WordpressPCL package.

From the dimensions of the image, I calculated the aspect ratio.根据图像的尺寸,我计算了纵横比。 With the aspect ratio, I was able to calculate the new Height of the image by multiplying the aspect ratio with the total width of the screen minus 20. 20 is the left margin + right margin of the StackLayout which is the parent of the image.使用纵横比,我可以通过将纵横比乘以屏幕的总宽度减去 20 来计算图像的新高度。20 是作为图像父级的 StackLayout 的左边距 + 右边距。

All the images are now full width to fit the width of the parent container and are not clipped (100% height).所有图像现在都是全宽以适应父容器的宽度,并且没有被剪裁(100% 高度)。

Code is as below (excluding the code which is responsible for parsing the rest of the content of the Wordpress post):代码如下(不包括负责解析Wordpress帖子内容的rest的代码):

Uri imageSource = new Uri(figure.GetAttributeValue("src", "").ToString());
Int32.TryParse(figure.GetAttributeValue("data-attachment-id", "").ToString(), out int mediaID);
string caption = null;
double aspectRatio = 0;
Task.Run(() =>
{
    Constants wpsite = new Constants();
    var client = new WordPressClient(wpsite.resturl);
    var caption_task = client.Media.GetByID(mediaID);
    caption_task.Wait();
    caption = caption_task.Result.Caption.Rendered;
    double height = caption_task.Result.MediaDetails.Height;
    double width = caption_task.Result.MediaDetails.Width;
    aspectRatio = height / width;
    var htmlCaption = new HtmlDocument();
    htmlCaption.LoadHtml(caption);
    caption = WebUtility.HtmlDecode(htmlCaption.DocumentNode.InnerText);
}).Wait();

Image image = new Image();
image.Source = imageSource;
image.Aspect = Aspect.AspectFit;
double maxWidth = Application.Current.MainPage.Width - 20;
double imageHeight = aspectRatio * maxWidth;
image.HeightRequest = imageHeight;

Label imageCaption = new Label();
imageCaption.Text = caption;
imageCaption.HorizontalTextAlignment = TextAlignment.Center;
imageCaption.FontSize = 12;
imageCaption.Margin = new Thickness(0, 0, 0, 10);

PostContainer.Children.Add(image);
PostContainer.Children.Add(imageCaption);

This is the output:这是 output:

输出

Try this one.试试这个。 It worked for me as intended.它按预期对我有用。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PGCubes.Main.Posts">
    <ScrollView>
        <StackLayout Margin="10"
                         HorizontalOptions="Center"
                         VerticalOptions="FillAndExpand"
                         x:Name="PostContainer">
            <Image x:Name="FeaturedImage"
                       HorizontalOptions="Center"/>
            <Label x:Name="Title"
                       FontSize="Title"
                       FontAttributes="Bold"
                       Margin="0, 20, 0, 10"/>
            <Label x:Name="PostMeta"
                       FontSize="Caption"
                       FontAttributes="None"
                       Margin="0, 0, 0, 0"/>
        </StackLayout>
    </ScrollView>
</ContentPage>

The code behind:后面的代码:

public partial class Posts : ContentPage
    {
        public Posts()
        {
            InitializeComponent();


            Title.Text = "Aims of this Mission";
            PostMeta.Text = "Lorem Ipsum is simply dummy text of " +
                "the printing and typesetting industry. Lorem Ipsum has been " +
                "the industry's standard dummy text ever since the 1500s, when " +
                "an unknown printer took a galley of type and scrambled it to " +
                "make a type specimen book. It has survived not only five centuries" +
                ", but also the leap into electronic typesetting, remaining essentially " +
                "unchanged. It was popularised in the 1960s with the release of Letraset " +
                "sheets containing Lorem Ipsum passages, and more recently with desktop " +
                "publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

            Image image = new Image();
            image.HeightRequest = 640;
            image.Source = "https://i.stack.imgur.com/r5pdVl.png";
            image.Aspect = Aspect.AspectFit;
            PostContainer.Children.Add(image);

        }
    }

The output from my samsung A30S我的三星 A30S 的 output 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM