重新想象 Windows 8.1 Store Apps (84) - 图像处理的新特性, Share Contract 的新特性

[源码下载]


重新想象 Windows 8.1 Store Apps (84) - 图像处理的新特性, Share Contract 的新特性



作者:webabcd


介绍
重新想象 Windows 8.1 Store Apps 之图像处理的新特性, Share Contract 的新特性

  • 图像处理的新特性 - 通过 RenderTargetBitmap 对 xaml 截图,以及保存图片
  • Share Contract 的新特性 - 增加 WebLink, ApplicationLink, 去掉了 Uri, “共享目标”可以自己 dismiss



示例
1、演示图像处理的新特性
RenderTargetBitmapDemo.xaml

<Page
    x:Class="Windows81.Image.RenderTargetBitmapDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows81.Image"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <StackPanel Width="200" Name="root" HorizontalAlignment="Left">
                <TextBlock Name="lblMsg" FontSize="14.667" Text="i am webabcd" />
                <Slider Width="200" />
                <Image Source="/Assets/Son.jpg" />
            </StackPanel>

            <Button Name="btnSaveImage" Content="将控件 root 中的内容保存为图片" Click="btnSaveImage_Click" Margin="0 10 0 0" />
            <Image Name="image" Margin="0 10 0 0" Stretch="None" HorizontalAlignment="Left" />

        </StackPanel>
    </Grid>
</Page>

RenderTargetBitmapDemo.xaml.cs

/*
 * 演示如何通过 RenderTargetBitmap 对 xaml 截图,以及如何将其保存为图片
 * 
 * 
 * RenderTargetBitmap - 用于对 xaml 截图,以及保存截图(其继承自 ImageSource)
 *     PixelWidth, PixelWidth - 宽和高
 *     RenderAsync() - 对指定的 UIElement 截图
 *     GetPixelsAsync() - 获取图像的二进制数据(Bgra8 格式,关于 Bgra8 格式请参见:http://www.cnblogs.com/webabcd/archive/2013/05/27/3101069.html)
 *     
 * 
 * 
 * 关于更多的图像处理基础,以及 WriteableBitmap 的应用请参见:
 * http://www.cnblogs.com/webabcd/archive/2013/05/27/3101069.html
 */

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Graphics.Display;
using Windows.Graphics.Imaging;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;

namespace Windows81.Image
{
    public sealed partial class RenderTargetBitmapDemo : Page
    {
        public RenderTargetBitmapDemo()
        {
            this.InitializeComponent();
        }

        private async void btnSaveImage_Click(object sender, RoutedEventArgs e)
        {
            // 实例化 RenderTargetBitmap 并对指定的 UIElement 截图,同时指定截图的宽和高
            RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
            await renderTargetBitmap.RenderAsync(root, (int)root.ActualWidth, (int)root.ActualHeight);

            // 由于 RenderTargetBitmap 继承自 ImageSource,所以可以直接显示(WriteableBitmap 也继承了 ImageSource)
            image.Source = renderTargetBitmap;


            // 获取截图的像素数据
            var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();

            // 实例化一个 FileSavePicker 用于保存图片
            var savePicker = new FileSavePicker();
            savePicker.DefaultFileExtension = ".png";
            savePicker.FileTypeChoices.Add(".png", new List<string> { ".png" });
            savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
            savePicker.SuggestedFileName = "snapshot.png";
            var saveFile = await savePicker.PickSaveFileAsync();
            if (saveFile == null)
                return;

            // 对二进制图像数据做 png 编码处理(关于更多的图像处理的示例请参见:http://www.cnblogs.com/webabcd/archive/2013/05/27/3101069.html
            using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
            {
                var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, fileStream);

                encoder.SetPixelData(
                    BitmapPixelFormat.Bgra8,
                    BitmapAlphaMode.Ignore,
                    (uint)renderTargetBitmap.PixelWidth,
                    (uint)renderTargetBitmap.PixelHeight,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    DisplayInformation.GetForCurrentView().LogicalDpi,
                    pixelBuffer.ToArray());

                // 保存 png 图片
                await encoder.FlushAsync();
            }
        }
    }
}



2、演示 Share Contract 的新特性
共享源:
ShareSource.xaml

<Page
    x:Class="Windows81.ShareContract.ShareSource"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows81.ShareContract"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" />

            <Button Content="Share WebLink" Click="Button_Click" Margin="0 10 0 0" />

            <Button Content="Share ApplicationLink" Click="Button_Click" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

ShareSource.xaml.cs

/*
 * 演示 Share Contract 的新特性(增加 WebLink, ApplicationLink, 去掉了 Uri, “共享目标”可以自己 dismiss)
 * 
 * 
 * 本例为“共享源”
 * 
 * 
 * 注:关于 Share Contract 的基础请参见:http://www.cnblogs.com/webabcd/archive/2013/07/04/3171085.html
 */

using System;
using Windows.ApplicationModel.DataTransfer;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Windows81.ShareContract
{
    public sealed partial class ShareSource : Page
    {
        // 当前需要分享的内容的类型
        private string _shareType = "Share WebLink";

        public ShareSource()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 初始化 DataTransferManager
            DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView();
            dataTransferManager.DataRequested += dataTransferManager_DataRequested;
            dataTransferManager.TargetApplicationChosen += dataTransferManager_TargetApplicationChosen;
        }

        void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
        {
            // 共享操作开始时(即弹出共享面板后),根据需要分享的内容的类型执行指定的方法
            switch (_shareType)
            {
                case "Share WebLink": // win 8.1 新增(一个 web 链接),去掉了原 Uri 共享(即在 win8.1 中将 Uri 拆分为 WebLink 和 ApplicationLink)
                    ShareWebLink(sender, args);
                    break;
                case "Share ApplicationLink": // win 8.1 新增(一个 app 的自定义协议),去掉了原 Uri 共享(即在 win8.1 中将 Uri 拆分为 WebLink 和 ApplicationLink)
                    ShareApplicationLink(sender, args);
                    break;
                default:
                    break;
            }
        }

        void dataTransferManager_TargetApplicationChosen(DataTransferManager sender, TargetApplicationChosenEventArgs args)
        {
            // 显示用户需要与其共享内容的应用程序的名称
            lblMsg.Text = "共享给:" + args.ApplicationName;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _shareType = (sender as Button).Content.ToString();

            // 弹出共享面板,以开始共享操作
            DataTransferManager.ShowShareUI();
        }

        // 共享 WebLink 的 Demo
        private void ShareWebLink(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            // 设置用于共享给“共享目标”的一些信息
            DataPackage dataPackage = args.Request.Data;
            dataPackage.Properties.Title = "Title";
            dataPackage.Properties.Description = "Description";
            // dataPackage.Properties.ApplicationListingUri - app 在商店中的 uri
            // dataPackage.Properties.ApplicationName

            // dataPackage.Properties.PackageFamilyName - win8.1 新增
            // dataPackage.Properties.LogoBackgroundColor - win8.1 新增,app 的 Square30x30Logo 图标的背景色(图标在“共享目标”的右上角显示)
            // dataPackage.Properties.ContentSourceWebLink - win8.1 新增
            // dataPackage.Properties.ContentSourceApplicationLink - win8.1 新增

            dataPackage.SetWebLink(new Uri("http://webabcd.cnblogs.com"));
        }

        // 共享 ApplicationLink 的 Demo
        private void ShareApplicationLink(DataTransferManager dtm, DataRequestedEventArgs args)
        {
            // 设置用于共享给“共享目标”的一些信息
            DataPackage dataPackage = args.Request.Data;
            dataPackage.Properties.Title = "Title";
            dataPackage.Properties.Description = "Description";
            // dataPackage.Properties.ApplicationListingUri - app 在商店中的 uri
            // dataPackage.Properties.ApplicationName

            // dataPackage.Properties.PackageFamilyName - win8.1 新增
            // dataPackage.Properties.LogoBackgroundColor - win8.1 新增,app 的 Square30x30Logo 图标的背景色(图标在“共享目标”的右上角显示)
            // dataPackage.Properties.ContentSourceWebLink - win8.1 新增
            // dataPackage.Properties.ContentSourceApplicationLink - win8.1 新增

            dataPackage.SetApplicationLink(new Uri("webabcd:webabcd.cnblogs.com"));
        }
    }
}


共享目标:
ShareTarget.xaml

<Page
    x:Class="Windows81.ShareContract.ShareTarget"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Windows81.ShareContract"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" Margin="0 10 0 0" />
            
            <Button Name="btnDismiss" Content="dismiss" Click="btnDismiss_Click" Margin="0 10 0 0" />

        </StackPanel>
    </Grid>
</Page>

ShareTarget.xaml.cs

/*
 * 演示 Share Contract 的新特性(增加 WebLink, ApplicationLink, 去掉了 Uri, “共享目标”可以自己 dismiss)
 * 
 * 
 * 本例为“共享目标”
 * 1、请在 manifest 中增加相应的声明,并增加共享“WebLink”和“ApplicationLink”的数据格式
 * 
 * 
 * 注:关于 Share Contract 的基础请参见:http://www.cnblogs.com/webabcd/archive/2013/07/04/3171085.html
 */

using System;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.DataTransfer.ShareTarget;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace Windows81.ShareContract
{
    public sealed partial class ShareTarget : Page
    {
        private ShareOperation _shareOperation;

        public ShareTarget()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 获取 ShareOperation 对象
            ShareTargetActivatedEventArgs shareTargetActivated = (ShareTargetActivatedEventArgs)e.Parameter;
            if (shareTargetActivated == null)
            {
                lblMsg.Text = "为了演示共享目标,请从共享源激活本页面";
                return;
            }
            _shareOperation = shareTargetActivated.ShareOperation;

            // 异步获取共享数据
            await Task.Factory.StartNew(async () =>
            {
                // 如果共享数据中包含 WebLink 格式数据,则显示之
                if (_shareOperation.Data.Contains(StandardDataFormats.WebLink))
                {
                    try
                    {
                        var uri = await _shareOperation.Data.GetWebLinkAsync();
                        OutputMessage("WebLink: " + uri.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }
                // 如果共享数据中包含 ApplicationLink 格式数据,则显示之
                if (_shareOperation.Data.Contains(StandardDataFormats.ApplicationLink))
                {
                    try
                    {
                        var uri = await _shareOperation.Data.GetApplicationLinkAsync();
                        OutputMessage("ApplicationLink: " + uri.AbsoluteUri);
                    }
                    catch (Exception ex)
                    {
                        OutputMessage(ex.ToString());
                    }
                }

                // 获取“共享源”传递过来的信息
                OutputMessage("ContentSourceApplicationLink: " + _shareOperation.Data.Properties.ContentSourceApplicationLink); // win 8.1 新增
                OutputMessage("ContentSourceWebLink: " + _shareOperation.Data.Properties.ContentSourceWebLink); // win 8.1 新增
                OutputMessage("PackageFamilyName: " + _shareOperation.Data.Properties.PackageFamilyName); // win 8.1 新增
                OutputMessage("LogoBackgroundColor: " + _shareOperation.Data.Properties.LogoBackgroundColor); // win 8.1 新增
                OutputMessage("ApplicationListingUri: " + _shareOperation.Data.Properties.ApplicationListingUri);
                OutputMessage("ApplicationName: " + _shareOperation.Data.Properties.ApplicationName);
            });
        }

        // 在 UI 上输出指定的信息
        async private void OutputMessage(string message)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                lblMsg.Text += message;
                lblMsg.Text += Environment.NewLine;
            });
        }

        private void btnDismiss_Click(object sender, RoutedEventArgs e)
        {
            // ShareOperation.DismissUI() - win8.1 中新增,用于 dismiss 掉当前的“共享目标”
            _shareOperation.DismissUI();
        }
    }
}

/*
 * 为了激活“共享目标”,需要在 App.xaml.cs 中 override 如下方法

// 通过共享激活应用程序时所调用的方法
protected override void OnShareTargetActivated(ShareTargetActivatedEventArgs args)
{
    var rootFrame = new Frame();
    rootFrame.Navigate(typeof(Windows81.ShareContract.ShareTarget), args);
    Window.Current.Content = rootFrame;

    Window.Current.Activate();
}
*/



OK
[源码下载]

posted @ 2014-07-17 08:48  webabcd  阅读(2121)  评论(2编辑  收藏  举报