xamarinccsprite

Load CCSprite Image from URL - CocosSharp + Xamarin.forms


I am working on Xamarin.Forms + CocosSharp Application. Here I want to load an image from an URL in cocoassharp using CCSprite. How can I achieve this? Normal CCSprite image is created like: var sprite = new CCSprite("image.png");


Solution

  • It is better to use async for stream and Read. I just did testing in place where that was not convenient but you should use async versions.

            var webClient = new HttpClient();
            var imageStream = webClient.GetStreamAsync(new Uri("https://xamarin.com/content/images/pages/forms/example-app.png")).Result;
            byte[] imageBytes = new byte[imageStream.Length];
            int read=0;
            do
            {
                read += imageStream.Read(imageBytes, read, imageBytes.Length- read);
            } while (read< imageBytes.Length);
            CCTexture2D texture = new CCTexture2D(imageBytes);
            var sprite = new CCSprite(texture);
    

    enter image description here