Xamarin.Forms Image图像控件

新建项目

启动 Visual Studio,新建名为 ImageTutorial 的 Xamarin.Forms 空白应用。

基础Image控件,MainPage.xaml

双击打开 MainPage.xaml,删除原有模板代码,替换:

<?xml version="1.0" encoding="utf-8"?>
<ContentPage xmlns="[http://xamarin.com/schemas/2014/forms](http://xamarin.com/schemas/2014/forms)"
             xmlns:x="[http://schemas.microsoft.com/winfx/2009/xaml](http://schemas.microsoft.com/winfx/2009/xaml)"
             x:Class="ImageTutorial.MainPage">
    <StackLayout Margin="20,35,20,20">
        <Image Source="[https://picsum.photos/id/237/600/400](https://picsum.photos/id/237/600/400)"
               HeightRequest="300" />
    </StackLayout>
</ContentPage>
Code language: HTML, XML (xml)

说明:原http图片链接报错,替换为https的公共测试图片地址,避免防盗链、明文http网络限制问题。

代码说明

  • Image:图像显示控件,用来展示图片。
  • Source:图片源,类型为ImageSource,支持网络URL、本地资源文件、嵌入资源三种方式加载图片。
  • HeightRequest="300":设置图片建议高度。

报错原因分析

java.io.IOException: Cleartext HTTP traffic to xxx not permitted
ImageLoaderSourceHandler: Could not retrieve image or image data was invalid
Code language: CSS (css)
  1. Cleartext HTTP traffic:Android 9(API28)及以上默认禁止明文HTTP(http://)请求,只允许HTTPS,这是最主要报错原因。
  2. 防盗链:原网站做了防盗链校验,直接在App请求图片会被服务器拒绝返回图片。

Aspect属性(图片缩放适配)

修改Image,增加Aspect控制图片缩放模式:

<Image Source="[https://picsum.photos/id/237/600/400](https://picsum.photos/id/237/600/400)"
       HeightRequest="300"
       Aspect="AspectFit"/>
Code language: HTML, XML (xml)

Aspect可选值:

  • AspectFit:保持图片比例,完整显示图片,空白区域留空(默认)
  • AspectFill:保持比例填满控件,图片超出部分会被裁剪
  • Fill:拉伸图片完全填满控件,图片可能变形

加载本地资源图片

把图片文件添加到共享项目,设置生成操作:Embedded resource,使用资源方式加载,不需要网络:

<Image Source="resource://ImageTutorial.Resources.dog.png"
       HeightRequest="300"/>
Code language: HTML, XML (xml)

知识点

  1. Image控件用于展示图片,核心属性Source,支持网络地址、本地文件、嵌入资源。
  2. HeightRequest/WidthRequest设置图片期望尺寸。
  3. Aspect控制图片缩放和裁剪策略。
  4. Android高版本默认禁止http明文请求,网络图片优先使用HTTPS链接;部分网站图片存在防盗链限制,无法直接加载。
  5. 网络图片加载失败常见原因:http明文限制、防盗链、图片地址失效、无网络权限。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注