Click or drag to resize

RuntimeImage Class

An image data container used with several image input and outputs in the API.
Inheritance Hierarchy
SystemObject
  Esri.ArcGISRuntime.UIRuntimeImage

Namespace:  Esri.ArcGISRuntime.UI
Assembly:  Esri.ArcGISRuntime (in Esri.ArcGISRuntime.dll) Version: 100.7.0.0
Syntax
C#
public class RuntimeImage : ILoadable

The RuntimeImage type exposes the following members.

Constructors
  NameDescription
Public methodRuntimeImage(Byte)
Initializes a new instance of the RuntimeImage class from an encoded image buffer
Public methodRuntimeImage(Uri)
Initializes a new instance of the RuntimeImage class from a Uri
Public methodRuntimeImage(Int32, Int32, Byte)
Initializes a new instance of the RuntimeImage class from a raw 32-bit RGBA image buffer
Top
Properties
  NameDescription
Public propertyHeight
Gets the height of the image in physical pixels
Public propertyLoadError
Gets the Exception associated with the last load error.
Public propertyLoadStatus
Gets the load status.
Public propertySource
Gets the URI endpoint for this image, or null if it's a local in-memory image
Public propertyWidth
Gets the width of the image in physical pixels
Top
Methods
  NameDescription
Public methodCancelLoad
Cancel loading metadata for the object.
Public methodStatic memberFromStreamAsync
Creates a RuntimeImage from a data stream
Public methodCode exampleGetEncodedBufferAsync
Returns the image data in the same format that it was created.
Public methodGetRawBufferAsync
Gets the raw 32-bit image buffer in RGBA order.
Public methodLoadAsync
Load the metadata for the object asynchronously.
Public methodRetryLoadAsync
Load or retry loading metadata for the object asynchronously.
Top
Events
  NameDescription
Public eventLoaded
Event that is raised when the object is done loading.
Public eventLoadStatusChanged
Event that is raised when the LoadStatus property changes.
Top
Extension Methods
  NameDescription
Public Extension MethodCode exampleToImageSourceAsyncOverloaded.
Converts a RuntimeImage to a platform-native image type.
(Defined by RuntimeImageExtensions.)
Public Extension MethodToImageSourceAsyncOverloaded.
Converts a RuntimeImage to a Xamarin.Forms image source.
(Defined by RuntimeImageExtensions.)
Top
Examples

Android

Example Name: TakeScreenshot

Take a screenshot of the map.

Code example screen shot.

C#
// Copyright 2016 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.

using Android.App;
using Android.OS;
using Android.Widget;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.Controls;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace ArcGISRuntime.Samples.TakeScreenshot
{
    [Activity(ConfigurationChanges = Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)]
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        "Take a screenshot",
        "MapView",
        "This sample demonstrates how you can take screenshot of a map. Click 'capture' button to take a screenshot of the visible area of the map. Created image is shown in the sample after creation.",
        "")]
    public class TakeScreenshot : Activity
    {
        // Hold a reference to the map view.
        private MapView _myMapView;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            Title = "Take a screenshot";

            CreateLayout();
            Initialize();
        }

        private void Initialize()
        {
            // Show an imagery basemap.
            _myMapView.Map = new Map(Basemap.CreateImagery());
        }

        private async void OnTakeScreenshotClicked(object sender, EventArgs e)
        {
            try
            {
                // Wait for rendering to finish before taking the screenshot.
                await WaitForRenderCompleteAsync(_myMapView);

                // Export the image from map view.
                RuntimeImage exportedImage = await _myMapView.ExportImageAsync();

                // Create an image button (this will display the exported map view image).
                ImageButton myImageButton = new ImageButton(this)
                {
                    // Define the size of the image button to be 2/3 the size of the map view.
                    LayoutParameters = new Android.Views.ViewGroup.LayoutParams((int) (_myMapView.Width * .667), (int) (_myMapView.Height * .667))
                };

                // Set the source of the image button to be that of the exported map view image.
                myImageButton.SetImageBitmap(await exportedImage.ToImageSourceAsync());

                // Make the image that was captured from the map view export to fit within (aka scale-to-fit) the image button.
                myImageButton.SetScaleType(ImageView.ScaleType.FitCenter);

                // Define a popup with a single image button control and make the size of the popup to be 2/3 the size of the map view.
                PopupWindow myPopupWindow = new PopupWindow(myImageButton, (int) (_myMapView.Width * .667), (int) (_myMapView.Height * .667));

                // Display the popup in the middle of the map view.
                myPopupWindow.ShowAtLocation(_myMapView, Android.Views.GravityFlags.Center, 0, 0);

                // Define a lambda event handler to close the popup when the user clicks on the image button.
                myImageButton.Click += (s, a) => myPopupWindow.Dismiss();
            }
            catch (Exception ex)
            {
                // Display any errors to the user if capturing the map view image did not work.
                AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
                alertBuilder.SetTitle("ExportImageAsync error");
                alertBuilder.SetMessage("Capturing image failed. " + ex.Message);
                alertBuilder.Show();
            }
        }

        private static Task WaitForRenderCompleteAsync(MapView mapview)
        {
            // The task completion source manages the task, including marking it as finished when the time comes.
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();

            // If the map is currently finished drawing, set the result immediately.
            if (mapview.DrawStatus == DrawStatus.Completed)
            {
                tcs.SetResult(null);
            }
            // Otherwise, configure a callback and a timeout to either set the result when
            // the map is finished drawing or set the result after 2000 ms.
            else
            {
                // Define a cancellation token source for 2000 ms.
                const int timeoutMs = 2000;
                var ct = new CancellationTokenSource(timeoutMs);

                // Register the callback that sets the task result after 2000 ms.
                ct.Token.Register(() =>
                    tcs.TrySetResult(null), false);


                // Define a local function that will set the task result and unregister itself when the map finishes drawing.
                void DrawCompleteHandler(object s, DrawStatusChangedEventArgs e)
                {
                    if (e.Status == DrawStatus.Completed)
                    {
                        mapview.DrawStatusChanged -= DrawCompleteHandler;
                        tcs.TrySetResult(null);
                    }
                }

                // Register the draw complete event handler.
                mapview.DrawStatusChanged += DrawCompleteHandler;
            }

            // Return the task.
            return tcs.Task;
        }

        private void CreateLayout()
        {
            // Create a new vertical layout for the app.
            LinearLayout layout = new LinearLayout(this) {Orientation = Orientation.Vertical};

            // Add a button to take a screen shot, with wired up event.
            Button takeScreenshotButton = new Button(this)
            {
                Text = "Capture"
            };
            takeScreenshotButton.Click += OnTakeScreenshotClicked;
            layout.AddView(takeScreenshotButton);

            // Add the map view to the layout.
            _myMapView = new MapView(this);
            layout.AddView(_myMapView);

            // Show the layout in the app.
            SetContentView(layout);
        }
    }
}
Examples

Xamarin Forms Android

Example Name: TakeScreenshot

Take a screenshot of the map.

Code example screen shot.

C#
// Copyright 2016 Esri.
// 
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an 
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific 
// language governing permissions and limitations under the License.

using Esri.ArcGISRuntime.Mapping;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Esri.ArcGISRuntime.UI;
using Xamarin.Forms;

namespace ArcGISRuntime.Samples.TakeScreenshot
{
    [ArcGISRuntime.Samples.Shared.Attributes.Sample(
        "Take a screenshot",
        "MapView",
        "This sample demonstrates how you can take screenshot of a map. Click 'capture' button to take a screenshot of the visible area of the map. Created image is shown in the sample after creation.",
        "")]
    public partial class TakeScreenshot : ContentPage
    {
        public TakeScreenshot()
        {
            InitializeComponent();
            Initialize();
        }

        private void Initialize()
        {
            // Show an imagery basemap.
            MyMapView.Map = new Map(Basemap.CreateImagery());
        }

        private async void OnTakeScreenshotClicked(object sender, EventArgs e)
        {
            try
            {
                // Wait for rendering to finish before taking the screenshot.
                await WaitForRenderCompleteAsync(MyMapView);

                // Export the image from the map view.
                RuntimeImage exportedImage = await MyMapView.ExportImageAsync();

                // Create layout for sublayers page
                // Create root layout
                StackLayout layout = new StackLayout();

                Button closeButton = new Button
                {
                    Text = "Close"
                };
                closeButton.Clicked += CloseButton_Clicked;

                // Create image bitmap by getting stream from the exported image.
                // NOTE: currently broken on UWP due to Xamarin.Forms bug https://github.com/xamarin/Xamarin.Forms/issues/5188. 
                var buffer = await exportedImage.GetEncodedBufferAsync();
                byte[] data = new byte[buffer.Length];
                buffer.Read(data, 0, data.Length);
                var bitmap = ImageSource.FromStream(() => new MemoryStream(data));
                Image image = new Image()
                {
                    Source = bitmap,
                    Margin = new Thickness(10)
                };

                // Add elements into the layout.
                layout.Children.Add(closeButton);
                layout.Children.Add(image);

                // Create internal page for the navigation page.
                ContentPage screenshotPage = new ContentPage()
                {
                    Content = layout,
                    Title = "Screenshot"
                };

                // Navigate to the sublayers page.
                await Navigation.PushAsync(screenshotPage);
            }
            catch (Exception ex)
            {
                await Application.Current.MainPage.DisplayAlert("Error", ex.ToString(), "OK");
            }
        }

        private static Task WaitForRenderCompleteAsync(Esri.ArcGISRuntime.Xamarin.Forms.MapView mapview)
        {
            // The task completion source manages the task, including marking it as finished when the time comes.
            TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();

            // If the map is currently finished drawing, set the result immediately.
            if (mapview.DrawStatus == DrawStatus.Completed)
            {
                tcs.SetResult(null);
            }
            // Otherwise, configure a callback and a timeout to either set the result when
            // the map is finished drawing or set the result after 2000 ms.
            else
            {
                // Define a cancellation token source for 2000 ms.
                const int timeoutMs = 2000;
                var ct = new CancellationTokenSource(timeoutMs);

                // Register the callback that sets the task result after 2000 ms.
                ct.Token.Register(() =>
                    tcs.TrySetResult(null), false);


                // Define a local function that will set the task result and unregister itself when the map finishes drawing.
                void DrawCompleteHandler(object s, DrawStatusChangedEventArgs e)
                {
                    if (e.Status == DrawStatus.Completed)
                    {
                        mapview.DrawStatusChanged -= DrawCompleteHandler;
                        tcs.TrySetResult(null);
                    }
                }

                // Register the draw complete event handler.
                mapview.DrawStatusChanged += DrawCompleteHandler;
            }

            // Return the task.
            return tcs.Task;
        }

        private async void CloseButton_Clicked(object sender, EventArgs e)
        {
            await Navigation.PopAsync();
        }
    }
}
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:esriUI="clr-namespace:Esri.ArcGISRuntime.Xamarin.Forms;assembly=Esri.ArcGISRuntime.Xamarin.Forms"
             xmlns:sampleViewer="clr-namespace:Forms.Resources;assembly=ArcGISRuntime"
             x:Class="ArcGISRuntime.Samples.TakeScreenshot.TakeScreenshot">
    <RelativeLayout>
        <esriUI:MapView x:Name="MyMapView" Style="{StaticResource MapWithFormStyle}"
                        BindingContext="{x:Reference Name=ResponsiveFormContainer}"/>
        <sampleViewer:ResponsiveFormContainer x:Name="ResponsiveFormContainer">
            <Button Text="Capture" 
                    Clicked="OnTakeScreenshotClicked" />
        </sampleViewer:ResponsiveFormContainer>
    </RelativeLayout>
</ContentPage>
See Also
Additional Examples
Hyperlink to ExampleDescription
AuthorMapCreate and save a map as an ArcGIS `PortalItem` (i.e. web map).
ReadShapefileMetadataRead a shapefile and display its metadata.
SymbolsFromMobileStyleOpen a mobile style (.stylx) and read its contents. Combine several symbols from the style into a single multilayer point symbol, then use it to display graphics in the map view.
TakeScreenshotTake a screenshot of the map.