我实现了一个Xamarin.Forms控件。我目前正在尝试的问题是,自定义渲染器的重写Draw()
方法会阻止UI(至少对于iOS平台而言)。我用Google搜索但没有成功。是否可以在后台执行绘图而不会阻止UI?
以下是iOS平台的简单渲染器的代码,用于演示此问题。
public class MyCustomRenderer : ViewRenderer
{
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
SetNeedsDisplay();
}
public override void Draw(CoreGraphics.CGRect rect)
{
var myControl = (MyControl)this.Element;
if (!myControl.IsRendered)
{
using (var context = UIGraphics.GetCurrentContext())
{
var token = CancellationToken.None;
var task = Task.Factory.StartNew(() => TimeConsumingRendering(context, token), token);
// task.Wait() blocks the UI but draws the desired graphics.
// When task.Wait() is commented out = the desired graphics doesn't get drawn and it doesn't block the UI
task.Wait();
}
}
}
private void TimeConsumingRendering(CGContext context, CancellationToken token)
{
try
{
for (int i = 0; i <= 100; i++)
{
token.ThrowIfCancellationRequested();
var delay = Task.Delay(50);
delay.Wait();
}
context.ScaleCTM(1f, -1f);
context.TranslateCTM(0, -Bounds.Height);
context.SetTextDrawingMode(CGTextDrawingMode.FillStroke);
context.SelectFont("Helvetica-Bold", 16f, CGTextEncoding.MacRoman);
context.SetFillColor(new CoreGraphics.CGColor(1f, 0f, 0f));
context.ShowTextAtPoint(0, 0, "Finished");
}
catch
{ }
}
}
答案 0 :(得分:0)
看起来唯一的解决方案是将耗时的绘图和绘图分离到实际控件上。
解决方案是
至少它对我有用。