制作一个用户头像选择器仿 WeGame

  • 制作一个用户头像选择Canvas为父控件所实现,展示图片使用ImagePath当作上方的蒙版;
  • Canvas:主要用途方便移动Image,设置ClipToBounds="True"裁剪为一个正方形200x200做为主要展示区域;
  • Image:展示需要裁剪的图片;
  • Path:CombinedGeometry[1]绘制蒙版大小200x200效果如下;
  • 当选择一个本地图片的时候判断宽与高谁更大,谁小就将它更改为200 ,另一边做等比缩放后给到DrawingVisual绘制一个新的BitmapFrame[2]Image控件做展示;
  • 当移动图片的时候右侧展示当前区域使用CroppedBitmap[3]进行裁剪并显示;
  • 源码Github[4] Gitee[5]


1)CropAvatar.xaml 代码如下;

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:controls="clr-namespace:WPFDevelopers.Controls">
    <ResourceDictionary.MergedDictionaries>
        <ResourceDictionary Source="Basic/ControlBasic.xaml"/>
    </ResourceDictionary.MergedDictionaries>

    <Style TargetType="controls:CropAvatar" BasedOn="{StaticResource ControlBasicStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type controls:CropAvatar}">
                    <Canvas x:Name="PART_Canvas" ClipToBounds="True">
                        <Image x:Name="PART_Image" Cursor="SizeAll" ></Image>
                        <Path x:Name="PART_Layout" 
                              Fill="{DynamicResource BlackSolidColorBrush}" 
                              Width="200" Height="200" 
                              Opacity=".5">
                            <Path.Data>
                                <CombinedGeometry GeometryCombineMode="Xor">
                                    <CombinedGeometry.Geometry1>
                                        <RectangleGeometry Rect="0,0,200,200"/>
                                    </CombinedGeometry.Geometry1>
                                    <CombinedGeometry.Geometry2>
                                        <EllipseGeometry Center="100,100" RadiusX="100" RadiusY="100"/>
                                    </CombinedGeometry.Geometry2>
                                </CombinedGeometry>
                            </Path.Data>
                        </Path>
                        <Grid x:Name="PART_Grid" Width="200" Height="200">
                            <Button x:Name="PART_ReplaceButton" Style="{StaticResource PathButton}"
                                    HorizontalAlignment="Right"
                                    VerticalAlignment="Top"
                                    Width="40" Height="40" ToolTip="更换图片"
                                    Visibility="Collapsed">
                                <Button.Content>
                                    <Path Data="{StaticResource PathReplace}"
                                          Fill="{StaticResource PrimaryNormalSolidColorBrush}"
                                          Height="15"
                                          Width="15"
                                          Stretch="Fill" />
                                </Button.Content>
                            </Button>
                            <Button x:Name="PART_AddButton" Style="{StaticResource PathButton}"
                                    Width="40" Height="40" ToolTip="选择图片">
                                <Button.Content>
                                    <Path Data="{StaticResource PathAdd}"
                                          Fill="{StaticResource PrimaryNormalSolidColorBrush}"
                                          Height="20"
                                          Width="20"
                                          Stretch="Fill" 
                                          RenderTransformOrigin="0.5,0.5" IsHitTestVisible="False">
                                        <Path.RenderTransform>
                                            <RotateTransform Angle="45"/>
                                        </Path.RenderTransform>
                                    </Path>
                                </Button.Content>
                            </Button>
                        </Grid>
                    </Canvas>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</ResourceDictionary>

2)CropAvatar.cs 代码如下;

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WPFDevelopers.Helpers;

namespace WPFDevelopers.Controls
{
    [TemplatePart(Name = CanvasTemplateName, Type = typeof(Canvas))]
    [TemplatePart(Name = ImageTemplateName, Type = typeof(Image))]
    [TemplatePart(Name = PathTemplateName, Type = typeof(Path))]
    [TemplatePart(Name = GridTemplateName, Type = typeof(Grid))]
    [TemplatePart(Name = ReplaceButtonTemplateName, Type = typeof(Button))]
    [TemplatePart(Name = AddButtonTemplateName, Type = typeof(Button))]
    public partial class CropAvatar : Control
    {
        private const string CanvasTemplateName = "PART_Canvas";
        private const string ImageTemplateName = "PART_Image";
        private const string PathTemplateName = "PART_Layout";
        private const string GridTemplateName = "PART_Grid";
        private const string ReplaceButtonTemplateName = "PART_ReplaceButton";
        private const string AddButtonTemplateName = "PART_AddButton";
        private Point point;
        private const int _size = 200;
        private bool isDown;
        private bool isLeft;
        private CroppedBitmap crop;
        private Canvas canvas;
        private Image image;
        private Path path;
        private Grid grid;
        private Button replaceButton, addButton;
        private int initialX, initialY, voffsetX, voffsetY;
        private double vNewStartX, vNewStartY, _StartX, _StartY, centerX, centerY;
        private BitmapFrame bitmapFrame;

        public ImageSource OutImageSource
        {
            get { return (ImageSource)GetValue(OutImageSourceProperty); }
            set { SetValue(OutImageSourceProperty, value); }
        }

        public static readonly DependencyProperty OutImageSourceProperty =
            DependencyProperty.Register("OutImageSource", typeof(ImageSource), typeof(CropAvatar), new PropertyMetadata(null));

        static CropAvatar()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CropAvatar), new FrameworkPropertyMetadata(typeof(CropAvatar)));
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            canvas = GetTemplateChild(CanvasTemplateName) as Canvas;
            canvas.Loaded += Canvas_Loaded;
            grid = GetTemplateChild(GridTemplateName) as Grid;
            image = GetTemplateChild(ImageTemplateName) as Image;
            image.MouseDown += Image_MouseDown;
            image.MouseMove += Image_MouseMove;
            image.MouseUp += Image_MouseUp;
            image.MouseLeave += Image_MouseLeave;
            path = GetTemplateChild(PathTemplateName) as Path;
            replaceButton = GetTemplateChild(ReplaceButtonTemplateName) as Button;
            replaceButton.Click += ReplaceButton_Click;
            addButton = GetTemplateChild(AddButtonTemplateName) as Button;
            addButton.Click += AddButton_Click;
        }

        private void Canvas_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is Canvas canvas)
            {
                var width = canvas.ActualWidth;
                var height = canvas.ActualHeight;
                centerX = (width - path.Width) / 2.0d;
                centerY = (height - path.Height) / 2.0d;
                canvas.Clip = new RectangleGeometry(new Rect(centerX, centerY, 200, 200)); 
                Canvas.SetLeft(path, centerX);
                Canvas.SetTop(path, centerY);
                Canvas.SetLeft(grid, centerX);
                Canvas.SetTop(grid, centerY);
            }
        }

        private void Image_MouseLeave(object sender, MouseEventArgs e)
        {
            isDown = false;
            if (isLeft)
                _StartX = Canvas.GetLeft(image);
            else
                _StartY = Canvas.GetTop(image);
        }

        private void Image_MouseUp(object sender, MouseButtonEventArgs e)
        {
            if (isDown)
            {
                var vPoint = e.GetPosition(this);
                if (isLeft)
                {
                    _StartX = Canvas.GetLeft(image);
                    initialX = voffsetX;
                }

                else
                {
                    _StartY = Canvas.GetTop(image);
                    initialY = voffsetY;
                }
            }
        }

        private void Image_MouseMove(object sender, MouseEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed && isDown)
            {
                var vPoint = e.GetPosition(this);
                if (isLeft)
                {
                    var voffset = vPoint.X - point.X;
                    vNewStartX = _StartX + voffset;
                    var xPath = Canvas.GetLeft(path);
                    if (vNewStartX <= xPath && vNewStartX >= -(bitmapFrame.Width - 200 - xPath))
                    {
                        Canvas.SetLeft(image, vNewStartX);
                        voffsetX = initialX - (int)voffset;
                        voffsetX = voffsetX < 0 ? 0 : voffsetX;
                        crop = new CroppedBitmap(bitmapFrame, new Int32Rect(voffsetX, 0, _size, _size));

                    }
                }
                else
                {
                    var voffset = vPoint.Y - point.Y;
                    vNewStartY = _StartY + voffset;
                    var yPath = Canvas.GetTop(path);
                    if (vNewStartY <= yPath && vNewStartY >= -(bitmapFrame.Height - 200 - yPath))
                    {
                        Canvas.SetTop(image, vNewStartY);
                        voffsetY = initialY - (int)voffset;
                        voffsetY = voffsetY < 0 ? 0 : voffsetY;
                        crop = new CroppedBitmap(bitmapFrame, new Int32Rect(0, voffsetY, _size, _size));
                    }
                }
                OutImageSource = crop;
            }
        }

        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            isDown = true;
            point = e.GetPosition(this);
        }

        private void ReplaceButton_Click(object sender, RoutedEventArgs e)
        {
            InitialImage();
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            InitialImage();
        }

        void InitialImage()
        {
            vNewStartX = 0;
            vNewStartY = 0;
            var uri = ControlsHelper.ImageUri();
            if (uri == null) return;
            var bitmap = new BitmapImage(uri);
            if (bitmap.Height > bitmap.Width)
            {
                double scale = (double)bitmap.Width / (double)path.Width;
                image.Width = _size;
                image.Height = (double)bitmap.Height / scale;
                isLeft = false;
            }
            else if (bitmap.Width > bitmap.Height)
            {
                double scale = (double)bitmap.Height / (double)path.Height;
                image.Width = (double)bitmap.Width / scale;
                image.Height = _size;
                isLeft = true;
            }
            bitmapFrame = ControlsHelper.CreateResizedImage(bitmap, (int)image.Width, (int)image.Height, 0);
            image.Source = bitmapFrame;
            if (image.Source != null)
            {
                replaceButton.Visibility = Visibility.Visible;
                addButton.Visibility = Visibility.Collapsed;
            }
            Canvas.SetLeft(grid, centerX);
            Canvas.SetTop(grid, centerY);
            _StartX = (canvas.ActualWidth - image.Width) / 2.0d;
            _StartY = (canvas.ActualHeight - image.Height) / 2.0d;
            Canvas.SetLeft(image, _StartX);
            Canvas.SetTop(image, _StartY);        
            if (isLeft)
            {
                initialX = (int)(image.Width - 200) / 2;
                initialY = 0;
                crop = new CroppedBitmap(bitmapFrame, new Int32Rect(initialX, 0, _size, _size));

            }
            else
            {
                initialY = (int)(image.Height - 200) / 2;
                initialX = 0;
                crop = new CroppedBitmap(bitmapFrame, new Int32Rect(0, initialY, _size, _size));
            }
            OutImageSource = crop;
        }
       
    }
}

3)CropAvatarWindow.xaml使用如下;

<ws:Window x:Class="WPFDevelopers.Samples.ExampleViews.CropAvatarWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"
        xmlns:ws="https://github.com/WPFDevelopersOrg.WPFDevelopers.Minimal"
        mc:Ignorable="d"  WindowStyle="ToolWindow" ResizeMode="NoResize"
        WindowStartupLocation="CenterScreen"
        Title="WPF 开发者-头像选择器" Height="450" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <wpfdev:CropAvatar x:Name="MyCropAvatar"/>
        <Image Grid.Column="1" Name="CropAvatarImage" Source="{Binding ElementName=MyCropAvatar,Path=OutImageSource}" 
               Stretch="Fill" Width="200" Height="200">
            <Image.Clip>
                <EllipseGeometry Center="100,100" RadiusX="100" RadiusY="100"/>
            </Image.Clip>
        </Image>
        <UniformGrid Grid.Row="1" Grid.ColumnSpan="2" 
                     HorizontalAlignment="Center" 
                     VerticalAlignment="Center">
            <Button  Content="保存" Click="btnSave_Click" Style="{StaticResource PrimaryButton}" Margin="4,0"/>
            <Button  Content="关闭" Click="btnClose_Click" Margin="4,0"/>
        </UniformGrid>
    </Grid>
</ws:Window>

4) CropAvatarWindow.xaml.cs 代码如下;

using System.Windows;

namespace WPFDevelopers.Samples.ExampleViews
{
    /// <summary>
    /// CropAvatarWindow.xaml 的交互逻辑
    /// </summary>
    public partial class CropAvatarWindow 
    {
        public CropAvatarWindow()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        private void btnClose_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
        }
    }
}

5) CropAvatarExample.xaml 使用如下;

<UserControl x:Class="WPFDevelopers.Samples.ExampleViews.CropAvatarExample"
             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" 
             xmlns:wpfdev="https://github.com/WPFDevelopersOrg/WPFDevelopers"
             xmlns:local="clr-namespace:WPFDevelopers.Samples.ExampleViews"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Button Content="图像选择器" VerticalAlignment="Center" HorizontalAlignment="Center" Click="Button_Click"/>
        <Image Grid.Column="1" Name="MyImage"
               Stretch="Fill" Width="200" Height="200">
            <Image.Clip>
                <EllipseGeometry Center="100,100" RadiusX="100" RadiusY="100"/>
            </Image.Clip>
        </Image>
    </Grid>
</UserControl>

6) CropAvatarExample.xaml.cs 代码如下;

using System.Windows.Controls;

namespace WPFDevelopers.Samples.ExampleViews
{
    /// <summary>
    /// CropAvatarExample.xaml 的交互逻辑
    /// </summary>
    public partial class CropAvatarExample : UserControl
    {
        public CropAvatarExample()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            var cropAvatarWindow = new CropAvatarWindow();
            if (cropAvatarWindow.ShowDialog() == true)
            {
                MyImage.Source = cropAvatarWindow.CropAvatarImage.Source;
            }
        }
    }
}

参考资料

[1]

CombinedGeometry: https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.media.combinedgeometry?view=netframework-4.0

[2]

BitmapFrame: https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.media.imaging.bitmapframe?view=windowsdesktop-6.0

[3]

CroppedBitmap: https://docs.microsoft.com/zh-cn/dotnet/api/system.windows.media.imaging.croppedbitmap?view=windowsdesktop-6.0

[4]

Github: https://github.com/WPFDevelopersOrg/WPFDevelopers

[5]

Gitee: https://gitee.com/WPFDevelopersOrg/WPFDevelopers

WPF 实现用户头像选择器的更多相关文章

  1. iOS常见用户头像的圆形图片裁剪常见的几种方法

    在开发中,基本上APP的用户头像的处理都需要把用户所上传的方形图片,处理为圆形图片.在这里就总结三种常见的处理圆形图片的方法. 1.使用位图上下文 2.使用UIView的layer进行处理 3.使用r ...

  2. ios/iphone手机请求微信用户头像错位BUG及解决方法

    转:http://www.jslover.com/code/527.html ios/iphone手机请求微信用户头像错位BUG及解决方法 发布时间:2014-12-01 16:37:01 评论数:0 ...

  3. 浅尝辄止WPF自定义用户控件(实现颜色调制器)

    主要利用用户控件实现一个自定义的颜色调制控件,实现一个小小的功能,具体实现界面如下. 首先自己新建一个wpf的用户控件类,我就放在我的wpf项目的一个文件夹下面,因为是一个很小的东西,所以就没有用mv ...

  4. app如何更换用户头像信息呢?不妨这样做

    对于现在的手机应用而言,要想获得更多的人的使用,就需要给用户更多的自由功能才行,这也是基于用户体验开发软件的核心思想,一切以用户为中心,想用户之所想,做用户之所需.今天我就来谈一谈刚学到的一个关于设置 ...

  5. android开发——用户头像

    最近,小灵狐得知了一种能够加快修炼速度的绝世秘法,那便是修炼android神功.小灵狐打算用android神功做一个app,今天他的修炼内容就是头像功能.可是小灵狐是个android小白啊,所以修炼过 ...

  6. php制作圆形用户头像——自定义封装类源代码

    思路 使用图层的方法设计,共需要创建3个图像层 1.底层:最后生成的图像 2.真实用户头像:作为中间层,用户上传的真实头像图片 3.圆形蒙版:作为最上层,在蒙版中绘制圆形,并设置为透明 如图: 代码如 ...

  7. App里面如何正确显示用户头像

    1.说明,一般用户头像在上传的时候都会处理为正方形,如果没有处理该怎么正确显示用户头像呢?解决方案:用css强制 在线地址移动端:戳这里 <div class="main-meimg& ...

  8. spring--mvc添加用户及用户头像上传

    spring--mvc添加用户及用户头像上传 添加用户步骤: 1.用ajax获取省份信息 2.添加用户 代码:register.jsp <meta http-equiv="Conten ...

  9. IOS 设置圆角用户头像

    在App中有一个常见的功能,从系统相册或者打开照相机得到一张图片,然后作为用户的头像.从相册中选取的图片明明都是矩形的图片,但是展示到界面上却变成圆形图片,这个神奇的效果是如何实现的呢? 请大家跟着下 ...

随机推荐

  1. redis & redis sentinel

    Redis 命令参考 Redis Sentinel Cheat Sheet Redis 哨兵节点之间相互自动发现机制(自动重写哨兵节点的配置文件) Redis哨兵模式(sentinel)学习总结及部署 ...

  2. 难对齐、难保障、难管理?一文了解字节跳动如何解决数据SLA治理难题

    基于字节跳动分布式治理的理念,数据平台数据治理团队自研了SLA保障平台,目前已在字节内部得到广泛使用,并支持了绝大部分数据团队的SLA治理需求,每天保障的SLA链路数量过千,解决了数据SLA难对齐.难 ...

  3. 零基础学Java第四节(字符串相关类)

    本篇文章是<零基础学Java>专栏的第四篇文章,文章采用通俗易懂的文字.图示及代码实战,从零基础开始带大家走上高薪之路! String 本文章首发于公众号[编程攻略] 在Java中,我们经 ...

  4. 445. Add Two Numbers II - LeetCode

    Question 445. Add Two Numbers II Solution 题目大意:两个列表相加 思路:构造两个栈,两个列表的数依次入栈,再出栈的时候计算其和作为返回链表的一个节点 Java ...

  5. c 语言彩票选号

    最近刚学了c语言,就做了个彩票选号程序练手玩玩,做的不好请见谅 1.分为前区(1-35)和后区(1-12)号码 2.先循环随机前区号在循环后区号 3.生成随机时数判断是否有重复值,和之前5期是否出现过 ...

  6. 【Java面试】JVM如何判断一个对象可以被回收

    Hi, 我是Mic. 今天分享一道一线互联网公司必问的面试题. "JVM如何判断一个对象可以被回收" 关于这个问题,来看看普通人和高手的回答. 普通人: 嗯.......... 高 ...

  7. 使用Rclone将Onedirve挂载到Linux本地

    1. centos挂载onedrive时, 需要安装fuse. # 安装fuse yum -y install fuse 2. 安装完fuse后使用rclone进行挂载 #创建挂载目录 mkdir - ...

  8. SpringCloud 配置管理:Nacos

    目录 统一配置管理 配置热更新 配置共享 多环境配置共享 多服务配置共享 统一配置管理 将配置交给 Nacos 管理的步骤: 在 Nacos 中添加配置文件. 在微服务中引入 nacos 的 conf ...

  9. 商户编号[Merchant Id]是什么

    1. Merchant Id是什么 2. Merchant Id 是有哪几个部分构成的 2.1 收单机构代码 2.2 商户地区代码 2.3 Merchant Category Code(MCC) 本文 ...

  10. 代码调用Rally的接口介绍

    1. 支持的语言 2. 创建APIKey 3. GetRequest 4. QueryRequest 5. CreateRequest 6. 参考资料 本文链接: https://www.cnblog ...