2016-04-08 17 views
3

我實現了一個Xamarin.Forms控件。我目前正在嘗試的問題是,重寫的自定義渲染器的Draw()方法會阻止UI(至少在iOS平臺上)。我google了,但沒有成功。是否可以在不阻擋用戶界面的情況下在後臺執行繪圖?重寫ViewRenderer的繪製方法阻止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

看起來,唯一的解決方案是將耗時的繪圖和繪圖分離到實際控制上。

的解決方案是

  1. 以生成一個背景(由事件觸發)的圖像。並且只能在Draw方法中使用它。
  2. 在覆蓋的Draw方法中使用生成的圖像。

至少它對我有用。