Screen snapshot Xamarin.Forms

痴心易碎 提交于 2019-12-20 06:45:31

问题


I have the following Xaml code:

<StackLayout>
        <Button Text="Take a picture" Clicked="Button_Clicked_1" />
        <Grid x:Name="MainPageBluePrintGrid" BackgroundColor="BlueViolet" HeightRequest="100">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition/>
            </Grid.RowDefinitions>

            <Label Text="A" Grid.Row="0" Grid.Column="0"/>
            <Label Text="B" Grid.Row="0" Grid.Column="1"/>
            <Label Text="C" Grid.Row="0" Grid.Column="2"/>

            <Image x:Name="image1" Grid.Row="1" Grid.Column="0"/>
            <Image x:Name="image2" Grid.Row="1" Grid.Column="1"/>
            <Image x:Name="image3" Grid.Row="1" Grid.Column="2"/>
        </Grid>


        <StackLayout BackgroundColor="BurlyWood">
            <Image x:Name="CapturedImage"/>
        </StackLayout>
    </StackLayout>        

The second row is images, which are picked by the user. Is it possible to take a screenshot only of the second row of GridView, and display it in the <Image x:Name="CapturedImage"/>. I have search how to do it, but I only came across full screen capture, which is not ideal in my case.


回答1:


Sounds like you want to create a snapshot of a specific Xamarin.Forms.View. You should wrap the 2nd Grid.Row by a single top level View that will contain the images as children. After that you could use platform specific capabilities to create a snapshot.

Android

public void MakeViewShot(Xamarin.Forms.View view)
{
    var nativeView = view.GetRenderer().View;
    var wasDrawingCacheEnabled = nativeView.DrawingCacheEnabled;
    nativeView.DrawingCacheEnabled = true;
    nativeView.BuildDrawingCache(false);
    var bitmap = nativeView.GetDrawingCache(false);
    // TODO: Save bitmap and return filepath
    nativeView.DrawingCacheEnabled = wasDrawingCacheEnabled;
}

iOS

public void MakeViewShot(Xamarin.Forms.View view)
{
    var nativeView = Xamarin.Forms.Platform.iOS.Platform.GetRenderer(view).NativeView;
    UIGraphics.BeginImageContextWithOptions(nativeView.Bounds.Size, opaque: true, scale: 0);
    nativeView.DrawViewHierarchy(nativeView.Bounds, afterScreenUpdates: true);
    var image = UIGraphics.GetImageFromCurrentImageContext();
    UIGraphics.EndImageContext();
    // TODO: Save bitmap and return filepath
}

Usage example:

<StackLayout
    x:Name="secondRow"
    Grid.Row="1">
    <Image x:Name="image1" />
    <Image x:Name="image2" />
    <Image x:Name="image3" />
</StackLayout>

MakeViewShot(secondRow);


来源:https://stackoverflow.com/questions/52152145/screen-snapshot-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!