简体   繁体   中英

iOS, Xamarin, UIView, Draw, dynamic animation doesn't works

I'm using MonoDevelop and xamarin for creating iOS application.

I have a view which looks like this:

public class MyView: UIView 
{
    private Timer _t = new Timer(1000);
    private int _i = 0;

    public MyView()
    {
        _t.Elapsed += (sender, e) => { 
             _i = (_i + 1) % 100;
             this.Draw(new Rectangle(0, 0, 110, 110)); 
         };
        _t.Enabled = true;
    }

    public override void Draw(RectangleF rect)
    {
        base.Draw(rect);
        var uiImage = UIImage.FromFile("myImage");
        var uiImageView = new UIIMageView(new Rectangle(_i, 0, 10, 10));
        uiImageView.Image = uiImage;
        AddSubView(uiIMageView);
    }
}

I expect that my image will move. But as a result I've only initial static image. Can anybody suggest approach how to do animation like described?

I would suggest modifying your code like so:

public MyView()
    {

        var uiImage = UIImage.FromFile("myImage");
        var uiImageView = new UIIMageView(new Rectangle(0, 0, 10, 10));
        uiImageView.Image = uiImage;
        AddSubView(uiIMageView);

        _t.Elapsed += (sender, e) => { 
             _i = (_i + 1) % 100;
             this.Draw(new Rectangle(_i, 0, 110, 110)); 
         };
        _t.Enabled = true;
    }

    public override void Draw(RectangleF rect)
    {
        base.Draw(rect);
        InvokeOnMainThread(()=>{
             uiImageView.Frame = rect;
        });
    }

I think part of your issue was that the timer Elapsed handler runs on a separate thread than the main UI Thread. Also you it'll be more efficient to not recreate the UIImageView each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM