PAYATHON 2026

在 ListView 中放置 Image 导致应用崩溃

排障赵师傅

结论

建议保留 hardwareAcceleration,不要用 android:anyDensity="false" 绕过异常。应在图片交给 Image 前限制解码后的位图尺寸。漫画中的超长图即使按宽度缩放,仍可能超过限制,因此还需要纵向切片,再交给 ListView 或 CollectionView 显示。

largeHeap="true" 通常也无法解决这个问题。异常发生在硬件加速的 Canvas 绘制阶段,并非单纯由 Java 堆内存不足引起。

异常原因

Android 实际绘制的是解码后的 Bitmap。一个只有几 MB 的 JPEG 文件解码为 ARGB_8888 后,每个像素通常需要 4 字节,内存占用大致为:

rowBytes × height

不考虑行对齐时,可以近似计算为:

width × height × 4

异常中的 109224768bytes 约为 104 MiB,说明传给硬件 Canvas 的单个位图已经过大。即使设备还有足够的剩余内存,Android 也可能拒绝这次绘制操作。

可滚动容器还会参与测量、回收以及硬件绘制列表的创建,所以同一张图片放在 StackLayout 和 ListView 中,表现可能不同。添加 Margin 后不再崩溃,只能说明布局和绘制路径发生了变化,无法保证换到其他设备、窗口尺寸或系统版本后仍然安全。

推荐处理方式

可以按以下优先级处理:

  1. 在图片服务器上生成适合移动端的版本。
  2. 将超长漫画页纵向切片,把每片限制在合理的像素高度内。
  3. 无法修改服务器时,在 Android 客户端进行区域解码和降采样。
  4. 为每个图片项设置明确的显示高度,减少滚动容器的重复测量。
  5. 使用虚拟化列表,只保留屏幕附近的图片项。

仅设置 WidthRequest、HeightRequest 或 Aspect="AspectFit" 未必有效。这些属性主要影响布局和显示尺寸,无法保证源图片会按目标尺寸解码。

优先在服务端处理

如果图片资源可控,建议按照客户端的显示宽度生成缩放版本。遇到特别高的漫画页,再按固定高度切片,例如:

page-001-0001.jpg
page-001-0002.jpg
page-001-0003.jpg

没有一个适合所有设备的固定切片高度,可以根据目标位图预算计算:

最大切片高度 ≈ 位图预算字节数 ÷ (目标宽度像素 × 每像素字节数)

使用 ARGB_8888 时,每个像素按 4 字节计算。还需要留出一定余量,因为解码、缩放、缓存以及列表中的相邻图片都会占用内存。

在服务端完成切片后,客户端不必先完整解码原图,也就不会在预处理阶段产生短时的内存峰值。

Android 客户端区域解码示例

无法修改图片服务器时,可以先把远程图片下载到缓存目录,再使用 BitmapRegionDecoder 分段解码。以下代码展示了主要处理过程,其中 inputPath 必须指向已经下载好的本地文件。

不同 .NET for Android 目标版本的可空标注和部分重载可能略有差异,请按项目使用的目标框架调整。

#if ANDROID
using Android.Graphics;
using Microsoft.Maui.Devices;
using Microsoft.Maui.Storage;

public sealed record ComicTile(
    string Path,
    double WidthRequest,
    double HeightRequest);

public static class ComicImagePreprocessor
{
    public static async Task<IReadOnlyList<ComicTile>> CreateTilesAsync(
        string inputPath,
        CancellationToken cancellationToken = default)
    {
        var display = DeviceDisplay.Current.MainDisplayInfo;
        var targetWidthPx = Math.Max(1, (int)display.Width);
        var targetWidthDip = display.Width / display.Density;

        return await Task.Run(
            () => CreateTilesCore(
                inputPath,
                targetWidthPx,
                targetWidthDip,
                cancellationToken),
            cancellationToken);
    }

    private static IReadOnlyList<ComicTile> CreateTilesCore(
        string inputPath,
        int targetWidthPx,
        double targetWidthDip,
        CancellationToken cancellationToken)
    {
        var boundsOptions = new BitmapFactory.Options
        {
            InJustDecodeBounds = true
        };

        BitmapFactory.DecodeFile(inputPath, boundsOptions);

        var sourceWidth = boundsOptions.OutWidth;
        var sourceHeight = boundsOptions.OutHeight;

        if (sourceWidth <= 0 || sourceHeight <= 0)
            throw new InvalidDataException("无法读取图片尺寸。");

        // 使用 2 的幂进行降采样。
        var inSampleSize = 1;

        while (sourceWidth / (inSampleSize * 2) >= targetWidthPx)
            inSampleSize *= 2;

        var decodedWidth = (int)Math.Ceiling(
            sourceWidth / (double)inSampleSize);

        // 24 MiB 是应用自行选择的保守预算,并非 Android 官方通用上限。
        const long maxTileBytes = 24L * 1024 * 1024;
        const int bytesPerPixel = 4;

        var maxTileHeightPx = (int)Math.Max(
            1,
            maxTileBytes / (decodedWidth * (long)bytesPerPixel));

        // 同时限制纹理高度,避免生成又高又窄的单个切片。
        maxTileHeightPx = Math.Min(maxTileHeightPx, 4096);

        var sourceTileHeight = Math.Max(
            inSampleSize,
            maxTileHeightPx * inSampleSize);

        var outputDirectory = System.IO.Path.Combine(
            FileSystem.CacheDirectory,
            "comic-tiles",
            Guid.NewGuid().ToString("N"));

        Directory.CreateDirectory(outputDirectory);

        var result = new List<ComicTile>();

        using var decoder = BitmapRegionDecoder.NewInstance(
            inputPath,
            false);

        var decodeOptions = new BitmapFactory.Options
        {
            InSampleSize = inSampleSize,
            InPreferredConfig = Bitmap.Config.Argb8888
        };

        var index = 0;

        for (var top = 0; top < sourceHeight; top += sourceTileHeight)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var bottom = Math.Min(
                sourceHeight,
                top + sourceTileHeight);

            var region = new Rect(
                0,
                top,
                sourceWidth,
                bottom);

            using var bitmap = decoder.DecodeRegion(
                region,
                decodeOptions);

            if (bitmap is null)
                throw new InvalidDataException("图片区域解码失败。");

            var outputPath = System.IO.Path.Combine(
                outputDirectory,
                $"{index:D4}.jpg");

            using (var stream = File.Create(outputPath))
            {
                if (!bitmap.Compress(
                        Bitmap.CompressFormat.Jpeg,
                        90,
                        stream))
                {
                    throw new IOException("图片切片写入失败。");
                }
            }

            var heightDip =
                targetWidthDip * bitmap.Height / bitmap.Width;

            result.Add(new ComicTile(
                outputPath,
                targetWidthDip,
                heightDip));

            index++;
        }

        return result;
    }
}
#endif

这段代码分别处理两个问题:

  • InSampleSize 用于降低解码宽度。
  • BitmapRegionDecoder 每次只解码原图的一部分,避免创建完整的超长 Bitmap。

如果先用 BitmapFactory.DecodeFile() 完整解码,再调用 Bitmap.CreateScaledBitmap(),缩放开始前仍可能分配出巨大的位图,因此不适合处理超长图。

在列表中显示切片

将预处理得到的切片集合绑定到列表。每个切片都有明确的宽度和高度,可以减少布局测量的不确定性。

<CollectionView
    ItemsSource="{Binding Tiles}"
    SelectionMode="None">

    <CollectionView.ItemsLayout>
        <LinearItemsLayout
            Orientation="Vertical"
            ItemSpacing="0" />
    </CollectionView.ItemsLayout>

    <CollectionView.ItemTemplate>
        <DataTemplate>
            <Image
                Source="{Binding Path}"
                WidthRequest="{Binding WidthRequest}"
                HeightRequest="{Binding HeightRequest}"
                Aspect="AspectFit"
                Margin="0" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>

也可以继续使用 ListView,但列表项应绑定切片,不要把整张超长图放进一个列表项:

<ListView
    ItemsSource="{Binding Tiles}"
    HasUnevenRows="True"
    SelectionMode="None"
    SeparatorVisibility="None">

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Image
                    Source="{Binding Path}"
                    WidthRequest="{Binding WidthRequest}"
                    HeightRequest="{Binding HeightRequest}"
                    Aspect="AspectFit"
                    Margin="0" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

其他注意事项

  • 不要同时下载和处理大量漫画页。应限制并发数量,避免多个切片任务的内存占用叠加。
  • 切片文件放入缓存目录后,应在漫画章节关闭或缓存过期时清理。
  • 不要把图片转换为 Base64 后再绑定。Base64 会增加数据体积,也不利于流式处理。
  • 使用第三方图片加载库时,需要确认它是否支持按目标尺寸解码和超长图切片。内存缓存或占位图功能无法解决单个位图过大的问题。
  • RGB_565 可以将每个像素的占用从通常的 4 字节降到 2 字节,但会损失颜色精度和透明度。它可以用于优化特定图片,无法代替切片。
  • android:largeHeap="true" 只会提高进程的可用堆上限,无法取消硬件 Canvas 对单个位图绘制大小的检查。
  • Margin="0,0,0,200" 只是布局层面的偶然规避,不适合作为正式修复方案。

保留硬件加速,并在图片进入控件前完成降采样和切片,可以同时保证滚动流畅度和稳定性。

备注:内容仅供参考。