来自 URL 的 Skiasharp 贷款图像并在 Xamarin Forms 中绘制 Canvas
Skiasharp loan image from URL and draw on Canvas in Xamarin Forms
我正在寻找一种从 URL 加载图像并使用 Xamarin 中的 Skiasharp 在 SKCanvas 上绘制的方法。
https://forums.xamarin.com/discussion/97717/skiasharp-get-skbitmap-from-url
我找到了上面的 link,但不知何故我的程序在使用示例时崩溃了。
在互联网上四处寻找后,我终于使代码可以工作了。下面是我的代码,其中包含更多内容,例如首先检查 URL 中是否存在文件,以及调整图像大小以适应整个 canvas 大小。
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 Source
到 url
。它使用 SkiaSharp 渲染图像。
或者,如果您喜欢冒险,您可以随时查看源代码中的实现并创建一个自定义的以满足您的需要 here
我正在寻找一种从 URL 加载图像并使用 Xamarin 中的 Skiasharp 在 SKCanvas 上绘制的方法。
https://forums.xamarin.com/discussion/97717/skiasharp-get-skbitmap-from-url
我找到了上面的 link,但不知何故我的程序在使用示例时崩溃了。
在互联网上四处寻找后,我终于使代码可以工作了。下面是我的代码,其中包含更多内容,例如首先检查 URL 中是否存在文件,以及调整图像大小以适应整个 canvas 大小。
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 Source
到 url
。它使用 SkiaSharp 渲染图像。
或者,如果您喜欢冒险,您可以随时查看源代码中的实现并创建一个自定义的以满足您的需要 here