Xamarin图像裁剪

时间:2016-10-12 17:23:25

标签: c# image xamarin xamarin.forms

我正试图制作自己的"滑块"通过使用图像在Xamarin形式内。我将下面的两张图像放在另一张图片上,另一张图片放在顶部作为"手柄"。当我移动手柄时,我想在手柄移动时裁剪空的和填充的图像(同时保持图像的纵横比)。我可以通过在手柄滑动时在相应图像上设置XWidth值来获得工作版本,但我无法使宽高比保持不变...就像在图像中一样调整大小但没有裁剪。将Aspect属性更改为Aspect.AspectFill时,裁剪行为非常奇怪。可能值得一提的是我通过LayoutBounds属性设置大小和位置。

graph fill image

graph empty image

长话短说,我的问题是如何在飞行中裁剪图像(从任何方向)?

内容放置页面的XAML:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
             prism:ViewModelLocator.AutowireViewModel="True"
             x:Class="MyProject.Views.PageView"
             Title="{Binding Title}">
  <AbsoluteLayout>
    <AbsoluteLayout x:Name="WidgetContent" />
  </AbsoluteLayout>
</ContentPage>

我的数据结构是一个小部件集合(WidgetViewModel),它有一组图像(ImageViewModel),它们被添加到布局中。此功能将图像添加到WidgetContent布局:

private void BuildImageView(ImageViewModel widgetImage)
{
    widgetImage.PropertyChanged += this.UpdateBounds;

    Image image = new Image()
    {
        BindingContext = widgetImage
    };

    // Set bindings for source
    image.SetBinding(Image.SourceProperty, "Source");
    image.SetBinding(Image.AspectProperty, "Aspect");

    // Set the size and bounds and scale to match screen size
    Rectangle bounds = this.ScaleBounds(widgetImage.LayoutBounds);

    // Redefine the value of the x/y positions after scaling
    widgetImage.XPosition = bounds.X;
    widgetImage.YPosition = bounds.Y;
    widgetImage.Width = bounds.Width;
    widgetImage.Height = bounds.Height;

    AbsoluteLayout.SetLayoutBounds(image, bounds);
    AbsoluteLayout.SetLayoutFlags(image, AbsoluteLayoutFlags.None);

    // Add the image to the layout
    this.widgetContent.Children.Add(image);
}

此功能处理移动手柄以及我尝试更新填充/空白尺寸的位置:

private void UpdateHandlePosition(Xamarin.Forms.Rectangle position, Xamarin.Forms.Point touchPoint)
{
    GraphWidget graphWidget = (GraphWidget)this.Widget;

    double newX = position.Left + touchPoint.X;
    double fillWidth = touchPoint.X + this.HandleDown.Width;

    if (newX + this.HandleDown.Width > position.Right)
    {
        newX = position.Right - this.HandleDown.Width;
        fillWidth = position.Width;
    }
    else if (newX < position.Left)
    {
        newX = position.Left;
        fillWidth = 0.1;
    }

    this.HandleDown.XPosition = newX;

    // HERE is my current attempt to resize the image                                                              
    ImageViewModel fillImage = this.Images.ElementAt(1);
    fillImage.Width = fillWidth;
}

0 个答案:

没有答案