我想要创建一个可以在屏幕上拖动的框,所以我创建了一个扩展Frame
的类(但是它也可以是AbsoluteLayout
,而不是BoxView
,因为我需要写点东西在那个盒子里)。
CLASS DragBox
using System;
using System.Diagnostics;
using Xamarin.Forms;
namespace PanGesture
{
public class DragBox : Frame
{
public DragBox()
{
var panGesture = new PanGestureRecognizer();
this.GestureRecognizers.Add(panGesture);
panGesture.PanUpdated += OnPanUpdated;
BorderColor = Color.Blue;
Padding = 4;
BackgroundColor = Color.Green;
Content = new Label
{
Text = "Word",
};
}
private void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
switch (e.StatusType)
{
case GestureStatus.Started:
Debug.WriteLine("DEBUG: start dragging");
break;
case GestureStatus.Running:
this.TranslationX = e.TotalX;
this.TranslationY = e.TotalY;
break;
case GestureStatus.Completed:
Debug.WriteLine("DEBUG: drag ended");
break;
}
}
}
}
并且在主页中,我只创建了一个DragBox实例
public partial class HomePage : ContentPage
{
public HomePage ()
{
InitializeComponent ();
DragBox box = new DragBox();
AbsoluteLayout.SetLayoutBounds(box, new Rectangle(0.1, 0.1, 0.2, 0.2));
AbsoluteLayout.SetLayoutFlags(box, AbsoluteLayoutFlags.All);
container.Children.Add(box);
}
}
问题是,当我开始拖动该框时,它具有闪烁的效果,如下图所示。怎么解决呢?还是有其他方法可以创建可拖动元素?
我在OnPanUpdated事件中修改了您的代码,可以在您身边尝试。
private void OnPanUpdated(object sender, PanUpdatedEventArgs e)
{
switch (e.StatusType)
{
case GestureStatus.Started:
Debug.WriteLine("DEBUG: start dragging");
break;
case GestureStatus.Running:
this.TranslationX = _xOffset + e.TotalX;
this.TranslationY = _yOffset + e.TotalY;
break;
case GestureStatus.Completed:
_xOffset = this.TranslationX;
_yOffset = this.TranslationY;
Debug.WriteLine("DEBUG: drag ended");
break;
}
}
如果我的回复对您有帮助,请记住将我的回复标记为答案,谢谢。