Avalonia 实现平滑拖动指定控件

avalonia,实现,平滑,拖动,指定,控件 · 浏览次数 : 284

小编点评

**Code Explanation:** The code provides an implementation of smooth dragging for a control named `DragControls`. **Key Concepts:** * **UserControl**: A custom control that inherits functionality from the `UserControl` class. * **DispatcherTimer**: An object that triggers a callback after a specified interval. * **Target Position**: The final destination point for the control's position. * **PointerPressed and PointerReleased Events**: Event handlers for when the mouse button is pressed and released on the control. * **OnTimerTick Event**: A callback triggered every 10 milliseconds to update the control's position. * **InitializeComponent()**: Method for initializing the control. * **OnPointerPressed()**: Method called when the mouse button is pressed. It starts dragging, records the initial position, and starts the timer. * **OnPointerReleased()**: Method called when the mouse button is released. It stops dragging, sets the target position, and stops the timer. * **OnPointerMoved()**: Method called when the mouse pointer moves. It updates the target position based on the current and previous positions. **Usage:** 1. Create an instance of `DragControls` control. 2. Set the target position of the control using the `_targetPosition` variable. 3. Set any other desired properties of the control. **Benefits:** * Smooth and natural dragging experience. * Event-driven handling for mouse press, move, and release events. * Adjustable target position. **Additional Notes:** * The code assumes the control has a `Window` as its root container. * The `_targetPosition` variable should be initialized with the desired target position of the control. * The animation and visual feedback should be implemented separately.

正文

Avalonia 实现平滑拖动指定控件

1.创建一个UserControl控件,并且添加以下代码

using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using Avalonia.Threading;
using Avalonia.VisualTree;

namespace Token;

/// <summary>
/// 实现拖动的控件
/// </summary>
public partial class DragControls : UserControl
{
    /// <summary>
    /// 记录上一次鼠标位置
    /// </summary>
    private Point lastMousePosition;

    /// <summary>
    /// 用于平滑更新坐标的计时器
    /// </summary>
    private DispatcherTimer _timer;

    /// <summary>
    /// 标记是否先启动了拖动
    /// </summary>
    private bool isDragging = false;

    /// <summary>
    /// 需要更新的坐标点
    /// </summary>
    private PixelPoint _targetPosition;

    public LoginStackPanelRight()
    {
        InitializeComponent();

        // 添加当前控件的事件监听
        PointerPressed += OnPointerPressed;
        PointerMoved += OnPointerMoved;
        PointerReleased += OnPointerReleased;

        // 初始化计时器
        _timer = new DispatcherTimer
        {
            Interval = TimeSpan.FromMilliseconds(10)
        };
        _timer.Tick += OnTimerTick;
    }

    /// <summary>
    /// 计时器事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void OnTimerTick(object sender, EventArgs e)
    {
        var window = this.FindAncestorOfType<Window>();
        if (window != null && window.Position != _targetPosition)
        {
            // 更新坐标
            window.Position = _targetPosition;
        }
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
    }

    private void OnPointerPressed(object sender, PointerPressedEventArgs e)
    {
        if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
        // 启动拖动
        isDragging = true;
        // 记录当前坐标
        lastMousePosition = e.GetPosition(this);
        e.Handled = true;
        // 启动计时器
        _timer.Start();
    }

    private void OnPointerReleased(object sender, PointerReleasedEventArgs e)
    {
        if (!isDragging) return;
        // 停止拖动
        isDragging = false;
        e.Handled = true;
        // 停止计时器
        _timer.Stop();
    }

    private void OnPointerMoved(object sender, PointerEventArgs e)
    {
        if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
        
        // 如果没有启动拖动,则不执行
        if (!isDragging) return;

        var currentMousePosition = e.GetPosition(this);
        var offset = currentMousePosition - lastMousePosition;
        var window = this.FindAncestorOfType<Window>();
        if (window != null)
        {
            // 记录当前坐标
            _targetPosition = new PixelPoint(window.Position.X + (int)offset.X,
                window.Position.Y + (int)offset.Y);
        }
    }
}

通过以上组件可以实现平滑拖动
效果如图

来着token的分享

与Avalonia 实现平滑拖动指定控件相似的内容:

Avalonia 实现平滑拖动指定控件

Avalonia 实现平滑拖动指定控件 1.创建一个UserControl控件,并且添加以下代码 using System; using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Markup.Xa

Avalonia 实现动态托盘

先下载一个gif图片,这里提供一个gif图片示例 在线GIF图片帧拆分工具 - UU在线工具 (uutool.cn) 使用这个网站将gif切成单张图片 创建一个Avalonia MVVM的项目,将图片copy进去 在项目文件中添加一下代码:

Avalonia中用FluentAvalonia+DialogHost.Avalonia实现界面弹窗和对话框

# Avalonia中用FluentAvalonia+DialogHost.Avalonia实现界面弹窗和对话框 本文是项目中关于 **`弹窗界面`** 设计的技术分享,通过 **`FluentAvalonia`+`DialogHost.Avalonia`** 开源nuget包来实现项目中需要 **

跨平台`ChatGpt` 客户端

跨平台ChatGpt 客户端 一款基于Avalonia实现的跨平台ChatGpt客户端 ,通过对接ChatGpt官方提供的ChatGpt 3.5模型实现聊天对话 实现创建ChatGpt的项目名称 ,项目类型是Avalonia MVVM , 添加项目需要使用的Nuget包

一个跨平台的`ChatGPT`悬浮窗工具

# 一个跨平台的`ChatGPT`悬浮窗工具 使用`avalonia`实现的`ChatGPT`的工具,设计成悬浮窗,并且支持插件。 ## 如何实现悬浮窗? 在使用`avalonia`实现悬浮窗也是非常的简单的。 实现我们需要将窗体设置成无边框 在`Window`根节点添加一下属性,想要在Linux下

Avalonia中的线性渐变画刷LinearGradientBrush

在WPF中使用Shape实现复杂线条动画后,尝试在Avalonia中也实现同样效果。尽管官方提供了从WPF到Avalonia的快速入门文档,但由于第一次使用Avalonia,体验过程中并不是很顺利,主要是卡在线性渐变画刷LinearGradientBrush的使用上。Avalonia中的线性渐变画刷

Avalonia 使用EFCore调用SQLite实现Singleton全局注册

# Avalonia 使用EFCore调用SQLite实现Singleton全局注册 ![image-20230720204001797](https://www.raokun.top/upload/2023/07/image-20230720204001797.png) 本篇博客是我的开源项目[T

avalonia自定义弹窗

对于使用avalonia的时候某些功能需要到一些提示,比如异常或者成功都需要对用户进行提示,所以需要单独实现弹窗功能,并且可以自定义内部组件,这一期将手动实现一个简单的小弹窗,并且很容易自定义 创建项目 实现我们需要创建一个avaloniaMVVM的项目模板 并且取名PopoverExample 然

在虚拟机VMware上安装OpenKylin开源操作系统

# 在虚拟机(VMware)上安装OpenKylin开源操作系统 今天我们一下学习下开放麒麟系统的安装。也是我的开源项目在OpenKylin上运行的实践。 希望通过该项目了解和学习Avalonia开发的朋友可以在我的github上拉取代码,同时希望大家多多点点star。 https://github

Avalonia应用在基于Linux的国产操作deepin上运行

deepin系统介绍 deepin(原名Linux Deepin)致力于为全球用户提供美观易用,安全可靠的 Linux发行版。deepin项目于2008年发起,并在2009年发布了以 linux deepin为名称的第一个版本。2014年4月更名为 deepin,在中国常被称为“深度操作系统”。 截