缩放用户控件中的裁剪像素

2023-12-24

我开发了一个用户控件。用户控件就像一个放大镜。 用户控件有一个图像按钮,它显示逐像素裁剪的图像。

StorageFile storageFile =
     await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/wallpaper.jpg", UriKind.RelativeOrAbsolute));
            using (Windows.Storage.Streams.IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read))
            {
                BitmapImage bitmapImage = new BitmapImage();
                await bitmapImage.SetSourceAsync(fileStream);


                WriteableBitmap writeableBitmap =
                    new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
                fileStream.Seek(0);
                await writeableBitmap.SetSourceAsync(fileStream);
                writeableBitmap = writeableBitmap.Crop(Convert.ToInt32(xValue), Convert.ToInt32(yValue), 100, 100);
                MagnifyTip.image1.ImageSource = writeableBitmap;

Now the MagnifyTip.image1 has an image source that is set to a cropped image . My requirenment is to zoom the cropped region and then assign it to the image source. The user control looks like this enter image description here Help would be appreciated


也许这对你有用,它和 WPF 允许的一样高效,因为代码中没有图像裁剪,它只是使用RenderTransform来施展魔法。运行下面的代码并将鼠标放在图像上,放大镜将如下所示:

XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Width="512"
        Height="512">
    <Grid>
        <Canvas MouseDown="FullImage_OnMouseDown"
                MouseMove="FullImage_OnMouseMove"
                MouseUp="FullImage_OnMouseUp">
            <Image Name="FullImage"
                   Source="http://www.mupin.it/wp-content/uploads/2012/06/lenna1.png" />
            <Border Name="BorderZoom"
                    Visibility="Visible"
                    Width="{Binding ImageZoomSize, FallbackValue='200'}"
                    Height="{Binding ImageZoomSize, FallbackValue='200'}">
                <Border.Clip>
                    <EllipseGeometry RadiusX="{Binding ImageZoomSizeHalf, FallbackValue=100}"
                                     RadiusY="{Binding ImageZoomSizeHalf, FallbackValue=100}"
                                     Center="{Binding CenterPoint, FallbackValue='100,100'}">

                    </EllipseGeometry>
                </Border.Clip>
                <Image Source="{Binding ElementName=FullImage, Path=Source}"
                       RenderTransformOrigin="0.5,0.5">
                    <Image.RenderTransform>
                        <TransformGroup>
                            <TranslateTransform X="{Binding Xt}"
                                                Y="{Binding Yt}" />
                            <ScaleTransform ScaleX="{Binding ZoomFactor, FallbackValue='8'}"
                                            ScaleY="{Binding ZoomFactor, FallbackValue='8'}" />
                        </TransformGroup>
                    </Image.RenderTransform>
                </Image>
            </Border>
        </Canvas>
    </Grid>
</Window>

这是背后的代码:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;

namespace WpfApplication1
{
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public MainWindow()
        {
            ZoomFactor = 8;
            ImageZoomSize = 200;
            InitializeComponent();

            BorderZoom.Visibility = Visibility.Hidden;
        }

        public double Xt { get; private set; }
        public double Yt { get; private set; }
        public double ZoomFactor { get; private set; }
        public int ImageZoomSize { get; private set; }
        public int ImageZoomSizeHalf { get { return ImageZoomSize/2; } }
        public Point CenterPoint { get { return new Point(ImageZoomSizeHalf, ImageZoomSizeHalf);} }


        private void FullImage_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            BorderZoom.Visibility = Visibility.Visible;
            FullImage_OnMouseMove(sender, e);
        }

        private void FullImage_OnMouseMove(object sender, MouseEventArgs e)
        {
            if (BorderZoom.Visibility == Visibility.Visible)
            {
                BorderZoom.Visibility = Visibility.Visible;
                var pos = e.GetPosition(FullImage);
                Canvas.SetLeft(BorderZoom, pos.X - ImageZoomSizeHalf);
                Canvas.SetTop(BorderZoom, pos.Y - ImageZoomSizeHalf);

                var isrc = FullImage.Source as BitmapSource;
                if(isrc == null) return;

                var h = (double)isrc.PixelHeight;
                var w = (double)isrc.PixelWidth;              

                Xt = pos.X* (-ImageZoomSize/w) + ImageZoomSize/2.0;
                Yt = pos.Y * (-ImageZoomSize / h) + ImageZoomSize / 2.0;

                OnNotifyPropertyChanged("Xt");
                OnNotifyPropertyChanged("Yt");
            }
        }

        private void FullImage_OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            BorderZoom.Visibility = Visibility.Hidden;
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void OnNotifyPropertyChanged(string propName)
        {
            if(PropertyChanged!= null) PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
}

UPDATE

根据要求,请参阅下面的代码,将放大笔尖包装在用户控件中,如下所示:

MagifiyingTipCtrl 的 XAML:

<UserControl x:Class="WpfApplication1.MagifiyingTipCtrl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>

        <Grid Name="ZoomedArea"  VerticalAlignment="Top"
              Visibility="Visible"
              Margin="15,15"
              Width="{Binding ZoomWidth, FallbackValue='136'}"
              Height="{Binding ZoomHeight, FallbackValue='128'}">
            <Grid.Clip>
                <EllipseGeometry RadiusX="{Binding ZoomWidthHalf, FallbackValue=68}"
                                 RadiusY="{Binding ZoomHeightHalf, FallbackValue=64}"
                                 Center="{Binding CenterPoint, FallbackValue='100,100'}">
                </EllipseGeometry>
            </Grid.Clip>
            <Image Source="{Binding SourceImage}"
                   RenderTransformOrigin="0.5,0.5">
                <Image.RenderTransform>
                    <TransformGroup>
                        <TranslateTransform X="{Binding Xt}"
                                            Y="{Binding Yt}" />
                        <ScaleTransform ScaleX="{Binding ZoomFactor, FallbackValue='8'}"
                                        ScaleY="{Binding ZoomFactor, FallbackValue='8'}" />
                    </TransformGroup>
                </Image.RenderTransform>
            </Image>
        </Grid>

        <Path Data="M25.533,0C15.457,0,7.262,8.199,7.262,18.271c0,9.461,13.676,19.698,17.63,32.338 c0.085,0.273,0.34,0.459,0.626,0.457c0.287-0.004,0.538-0.192,0.619-0.467c3.836-12.951,17.666-22.856,17.667-32.33 C43.803,8.199,35.607,0,25.533,0z M25.533,32.131c-7.9,0-14.328-6.429-14.328-14.328c0-7.9,6.428-14.328,14.328-14.328 c7.898,0,14.327,6.428,14.327,14.328C39.86,25.702,33.431,32.131,25.533,32.131z"
              Fill="#FFF4F4F5"
              Stretch="Fill"
              Stroke="Black"
              UseLayoutRounding="False"
              Height="227"
              Width="171" />
    </Grid>
</UserControl>

MagifiyingTipCtrl 的隐藏代码:

using System.Windows.Media.Imaging;

namespace WpfApplication1
{
    public partial class MagifiyingTipCtrl : UserControl
    {
        public MagifiyingTipCtrl()
        {
            ZoomFactor = 8;
            ZoomWidth = 136;
            ZoomHeight = 128;

            InitializeComponent();
        }

        public static readonly DependencyProperty SourceImageProperty =
            DependencyProperty.Register("SourceImage", typeof (BitmapSource), typeof (MagifiyingTipCtrl));

        public static readonly DependencyProperty XtProperty =
            DependencyProperty.Register("Xt", typeof(double), typeof(MagifiyingTipCtrl));

        public static readonly DependencyProperty YtProperty =
            DependencyProperty.Register("Yt", typeof(double), typeof(MagifiyingTipCtrl));


        public BitmapSource SourceImage
        {
            get { return (BitmapSource)GetValue(SourceImageProperty); }
            set { SetValue(SourceImageProperty, value); }
        }

        public double Xt
        {
            get { return (double)GetValue(XtProperty); }
            set { SetValue(XtProperty, value); }
        }

        public double Yt
        {
            get { return (double)GetValue(YtProperty); }
            set { SetValue(YtProperty, value); }
        }

        public void SetPosition(Point pos)
        {
            if (SourceImage == null) return;

            var h = (double)SourceImage.PixelHeight;
            var w = (double)SourceImage.PixelWidth;

            Xt = pos.X * (-ZoomWidth / w) + ZoomWidth / 2.0;
            Yt = pos.Y * (-ZoomHeight / h) + ZoomHeight / 2.0;
        }

        public double ZoomFactor { get; private set; }
        public int ZoomWidth { get; private set; }
        public int ZoomHeight { get; private set; }

        public int ZoomWidthHalf { get { return ZoomWidth / 2; } }
        public int ZoomHeightHalf { get { return ZoomHeight / 2; } }

        public Point CenterPoint { get { return new Point(ZoomWidthHalf, ZoomHeightHalf); } }
    }
}

主窗口的 XAML:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:wpfApplication1="clr-namespace:WpfApplication1"
        Title="MainWindow"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Width="512"
        Height="512">
    <Grid>
        <Canvas MouseDown="FullImage_OnMouseDown"
                MouseMove="FullImage_OnMouseMove"
                MouseUp="FullImage_OnMouseUp">
            <Image Name="FullImage"
                   Source="http://www.mupin.it/wp-content/uploads/2012/06/lenna1.png" />

            <wpfApplication1:MagifiyingTipCtrl x:Name="MagnifiyingTip"
                                               SourceImage="{Binding ElementName=FullImage, Path=Source}" />
        </Canvas>
    </Grid>
</Window>

主窗口的隐藏代码:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void FullImage_OnMouseDown(object sender, MouseButtonEventArgs e)
        {
            MagnifiyingTip.Visibility = Visibility.Visible;
            FullImage_OnMouseMove(sender, e);
        }

        private void FullImage_OnMouseMove(object sender, MouseEventArgs e)
        {
            if (MagnifiyingTip.Visibility == Visibility.Visible)
            {
                MagnifiyingTip.Visibility = Visibility.Visible;
                var pos = e.GetPosition(FullImage);
                Canvas.SetLeft(MagnifiyingTip, pos.X - MagnifiyingTip.ActualWidth/2);
                Canvas.SetTop(MagnifiyingTip, pos.Y - MagnifiyingTip.ActualHeight);
                MagnifiyingTip.SetPosition(pos);
            }
        }

        private void FullImage_OnMouseUp(object sender, MouseButtonEventArgs e)
        {
            MagnifiyingTip.Visibility = Visibility.Hidden;
        }
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

缩放用户控件中的裁剪像素 的相关文章

  • 从 C 中的 char* 获取单个字符

    有没有办法在 C 中逐字符遍历或从 char 中提取单个字符 考虑以下代码 现在获得单个角色的最佳方式是什么 建议我一种不使用任何字符串函数的方法 char a STRING 其他方式 char i for i a i i i points
  • is_integral 与 is_integer:其中之一是多余的吗?

    是积分 http en cppreference com w cpp types is integral and 是整数 http en cppreference com w cpp types numeric limits is inte
  • dup2() 和 exec()

    include
  • binary_log_types.h:没有这样的文件或目录

    我正在编译一个小型 mysql C 项目并且 遇到以下错误 C Program Files x86 MySQL MySQL Server 5 7 include mysql com h 22 30 fatal error binary lo
  • 计算复杂数组的abs()值的最快方法

    我想计算 C 或 C 中复杂数组元素的绝对值 最简单的方法是 for int i 0 i lt N i b i cabs a i 但对于大向量来说 速度会很慢 有没有办法加快速度 例如使用并行化 语言可以是 C 或 C 鉴于所有循环迭代都是
  • NHibernate IQueryable 集合作为 root 的属性

    我有一个根对象 它有一个集合属性 例如 I have a Shelf object that has Books Now public class Shelf public ICollection
  • 增量决策树 C++ 实现

    有谁知道决策树分类器的增量实现吗 这样 当您将新实例添加到训练集中时 它可以根据现有决策树分类器以低计算量并尽可能快地生成最佳决策树分类器 换句话说 我有一个最优决策树分类器集A 其中命名为T 1 现在我想添加实例X to set A并找到
  • 我要恢复我的记忆!我怎样才能真正处理一个控件?

    我正在制作一个应用程序 它创建大量的窗口控件 按钮和标签等 它们都是通过函数动态生成的 我遇到的问题是 当我删除控件并处置它们时 它们不会从内存中删除 void loadALoadOfStuff while tabControlToClea
  • 我可以在 C++ 中重写非虚函数吗

    我想知道我可以重写 C 中的非虚函数吗 因为我在使用 C 时发现了这个问题override关键字我的代码如下 class A public void say cout lt lt From A n class B public A publ
  • 如何使用 ProtoGen 从 proto 文件生成结构

    我们一直在使用 protobuf net ProtoGen 从 proto 文件生成 C cs 文件 我们希望代替类来生成结构 例如 DataContract public struct Entity1 ProtoMember 1 publ
  • C 中的链表数组:初始化和插入?

    我需要创建一个链表数组 如图所示 这就是我到目前为止所做的 typedef struct Node int data struct Node next Node int main void Node link 5 for int q 0 q
  • C++:LPWSTR 在 cout 中打印为地址

    我有一个类型变量LPTSTR 我打印到std cout with lt lt 在 ANSI 系统中 不知道它是在哪里确定的 它工作得很好 它打印了字符串 现在 在 Unicode 系统中 我得到的是十六进制地址而不是字符串 那么 为什么LP
  • 我可以对(非成员)函数使用部分模板特化吗?

    我试图在 非成员 函数上使用部分模板专业化 但我在语法上遇到了问题 我在 StackOverflow 中搜索了其他部分模板专业化问题 但这些问题涉及类或成员函数模板的部分专业化 作为起点 我有 struct RGBA RGBA uint8
  • 为什么未到达的 try-catch 块会增加运行时间?

    我目前正在创建自己的容器库 但我已经看到无法访问 if 语句无效 try catch阻止增加运行时间 这是我的测试 Vector cpp template
  • 使用非字符串作为字符串(而不是自动使用 ToString)时如何显示错误?

    建议的重复确实是一个类似的问题 然而 答案只涵盖一种选择 禁用 ToString 本身 还有其他可能的解决方案 例如让 Visual Studio 警告我 或者不调用 ToString 仔细阅读那里的答案 他认为is调用 只是解释说没有办法
  • 将多个 Blob 输入传递到 QueueTrigger Azure 函数的最佳方法

    问题 触发后 生成 3 个 XML 文件 完成后将它们通过 ftp 传输到站点 目前的方法 我有一个 HTTP 触发器 Azure 函数 运行时将构造 3 个 XML 文件并将它们保存到 Azure 存储 Blob 容器中 由于有多个输出
  • 在Framework 4.6项目中使用.net core DLL

    我已经在 net core 2 0 中构建了一个 DLL 现在我想在使用 net 4 6 1 框架的 WinForms 项目中使用它 我可以引用该 dll 但收到 System IO FileLoadException 表示找不到 Syst
  • 使用 MVC5、Ajax、C# 和 MSSQL Server 级联 DropdownList

    我对来自 Windows 窗体和三层架构的 MVC 非常陌生 我试图找出使用从数据库填充的级联下拉列表 DDL 我使用 MS SQL Server 2012 VS 2013 目前我正在研究用户调查问卷 用户可以从 DDL 的多个答案中进行选
  • char[length]初始化并处理

    我定义了一个字符数组 char d 6 如果我在以下方面有误 请纠正我 此时没有为变量分配内存d 现在我要初始化它 d aaaaa 这种初始化之后 就不需要释放内存了 它将自动完成 我怎么知道是否char 被初始化了吗 我正在寻找类似的模式
  • C#:如何处理乱序 TCP 数据包?

    请有人解释一下如何处理乱序数据包 我使用原始套接字来捕获数据包 并在数据包到来时解析它们 但其中一些数据包的顺序错误 例如 ID 标志 16390 PSH ACK 16535 PSH ACK 16638 确认 16640 PSH ACK 1

随机推荐

  • VS Code - git 存储库有太多活动更改,仅启用 Git 功能的子集

    我正在设置 VS Code 以处理保存在 BitBucket 中的现有 Salesforce 项目 我将存储库克隆到我的设备 现在当我打开 VS Code 时 我收到消息 C Users 我的存储库目录 处的 git 存储库有太多活动更改
  • 如何在Godot 4.0游戏引擎中实现可组合的角色/技能系统?

    我目前正在使用 Godot 尝试 MOBA 风格游戏的原型 我正在努力寻找一种管理角色及其技能的方法 所有角色都将具有相似的属性 姓名 生命值 奔跑速度 力量等 然而 所有角色的技能都会有所不同 尽管有些角色非常相似 例如基于投射物的技能将
  • 如何在 Buddypress 中获取用户名/显示名称?

    在 buddypress 默认模板中 发布某个活动的用户名显示如下 bp activity action 但这带来的不仅仅是用户名 有没有更简单的方法来获取用户对象 名称 WordPress 获取用户数据功能不起作用 因为它显示页面作者 而
  • Rails 日期验证与年龄

    在我的 Rails 应用程序中 有一个注册表单 其中包含 DOB 字段 用户的年龄不必超过 18 岁 我如何对此进行验证 我的出生日期格式是 mm dd yy 这个语法非常有趣 你可以这样做 old enough 10 23 2000 to
  • 如何在使用 cardUseCompatPadding 时覆盖 CardView 中的标准填充?

    当我使用 cardUseCompatPadding 在卡片视图中显示阴影时 顶部填充比左侧填充大 如何使两个填充相等 因为我的丝带看起来不漂亮 它在上面更大 谢谢
  • 在博览会应用程序上请求通知权限时收到错误

    我有一个简单的代码 要求过去有效的通知权限 但突然间 它给了我这个错误 错误 调用本机方法时遇到异常 在模块 ExpoNotificationPermissionsModule 上执行导出方法 requestPermissionsAsync
  • 如何使用 pybabel 在 jinja 2.10 {% trans %} 中转义 '%' 字符?

    我正在使用 jinja 2 10 和 pybabel 当我的模板包含以下代码 trans 块内有 字符 时 pybabel compile 不会翻译该字符串 提取的字符串 在 po 中 正常 但在结果页面上它根本没有被翻译 h3 class
  • 从 python 中的函数返回左值

    抱歉 我是 Python 新手 虽然这似乎是一个非常基本的问题 但在询问听众之前 我做了尽职调查 试图避免真正愚蠢的问题 我试图找出从函数返回左值的正确习惯用法 假设我有一个包含 64 个对象的容器 并且我希望能够返回对这些对象的引用 cl
  • Wordpress 中的 PhP 联系表单

    所以我买了一个主题 它有一个简单的 PHP 联系表单 允许用户互相发送消息 但是当发件人填写表单并提交时 电子邮件来自我的默认 WordPress 管理员电子邮件 而不是用户输入的电子邮件地址表格 因此 如果收件人尝试回复他们的电子邮件 邮
  • Google Apps 脚本 - 从模板创建的每个文档中都出现“需要授权”

    我有一个 Google 文档 它有一个自定义 UI 菜单 其中包含一个选项 可以将新页面添加到文档并用一些数据填充它 我使用此文档作为模板 通过 Web 应用程序为单个用户创建许多其他文档 因此 我的用户来到我的 web 应用程序 单击生成
  • Boost::bind 和 Boost Phoenix::bind 有什么区别?

    Boost bind 和 Boost Phoenix bind 有什么区别 phoenix bind就好像lambda bind返回一个表达式模板的函数 该模板记录它必须调用给定的函数 它们被设计为分别与phoenix 和lambda 一起
  • 使用 jQuery 克隆

    我有一个允许用户推荐朋友的表格 我想在 朋友电子邮件 和 朋友姓名 这两个输入字段下方添加一个链接 该链接将克隆 朋友框 一次并将其添加到下面 另外 好友邮箱 和 好友姓名 的name属性为name friend email 0 and n
  • 如何将张量转换为字符串

    我正在测试 tf data 这是现在批量提供数据的推荐方法 但是 我正在加载自定义数据集 因此我需要 str 格式的文件名 但是当创建 tf Dataset from tensor slices 时 它们是 Tensor 对象 def lo
  • 根据列聚合过滤选定的列

    我希望仅选择唯一值少于 3 个的列 我可以通过生成布尔掩码pl all n unique lt 3 但我不知道是否可以通过 Polars API 使用该掩码 目前 我正在通过 python 解决这个问题 有更惯用的方法吗 import po
  • Logcat 消息在短时间内消失

    有时 eclipse logcat 消息在关闭应用程序一小段时间后就会消失 大多不会那么短 如何让它永远不会自动消失 编辑 我的设备仍然连接 以及如何将其设置为即使在设备断开连接并在下次启动之前清除后也显示日志 这也发生在我身上 设备已连接
  • Perl 正则表达式 'e' (eval) 修饰符带 s///

    我在理解 e 正则表达式修饰符的简单用法时遇到了一些困难 my var testing In this string we are var the e modifier s w 1 ee print 返回 在此字符串中 我们正在测试 e 修
  • 如何使用 DropDownList 的 SelectedIndexChanged 事件

    我有两个DropDownList在我的网络表单中 当我在第一个下拉列表中选择一个值时 我希望在第二个下拉列表中自动选择一个相关值 这就是我目前所拥有的 table tr td td tr table
  • 合并两个 Sass 文件

    我想即时将两个 sass 文件合并在一起 例如 如果我有 some class color white and some class background color red 那么最终结果将是 some class color white
  • 无法上传 > ~2GB 到 Google Cloud Storage

    追踪如下 相关的Python片段 bucket get bucket location bucket blob bucket blob location path blob upload from filename source path
  • 缩放用户控件中的裁剪像素

    我开发了一个用户控件 用户控件就像一个放大镜 用户控件有一个图像按钮 它显示逐像素裁剪的图像 StorageFile storageFile await StorageFile GetFileFromApplicationUriAsync