Skiasharp从URL借用图片,并在Xamarin表单的画布上绘制



我正在寻找一种从URL加载图像并使用Xamarin中的Skiasharp在SKCanvas上绘制的方法。

https://forums.xamarin.com/discussion/97717/skiasharp-get-skbitmap-from-url

我找到了上面的链接,但不知怎么的,我的程序在这个例子中崩溃了。

在浏览了互联网后,我终于让代码正常工作了。下面是我的代码,其中包括一些内容,例如首先检查URL中是否存在文件,以及调整图像大小以适应整个画布的大小。

HttpWebResponse response = null;
var request = (HttpWebRequest) WebRequest.Create(url);
request.Method = "HEAD";
request.Timeout = 2000; // miliseconds
try 
{
response = (HttpWebResponse) request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK) //Make sure the URL is not empty and the image is there
{
// download the bytes
byte[] stream = null;
using(var webClient = new WebClient()) 
{
stream = webClient.DownloadData(url);
}
// decode the bitmap stream
resourceBitmap = SKBitmap.Decode(stream);
if (resourceBitmap != null) 
{
var resizedBitmap = resourceBitmap.Resize(info, SKFilterQuality.High); //Resize to the canvas
canvas.DrawBitmap(resizedBitmap, 0, 0);
}
}
}
catch(Exception ex) 
{
}
finally 
{
// Don't forget to close your response.
if (response != null) 
{
response.Close();
}
}

您可以使用FFImageLoading库,它支持开箱即用的Image Sourceurl。它使用SkiaSharp来渲染图像。或者,如果你有冒险精神,你可以在源代码中查看实现,并在这里创建一个自定义的实现来满足你的需求

最新更新