蓝色天空.知识 · 实践 · 创造
我的收藏
Android 教程目录 156章
课程介绍
Android / LEARN BY DOING

2.3.4 ImageView(图像视图)

核对 Android ImageView 中 src 与 background 的渲染差异、adjustViewBounds 配合 maxWidth/maxHeight 等比缩放、全部 8 种 ScaleType 矩阵变换规则及圆形 ImageView 的实现与现代演进。

学完这一章,你能够

  • 核对 Android ImageView 中 src 与 background 的渲染差异、adjustViewBounds 配合 maxWidth/maxHeight 等比缩放、全部 8 种 ScaleType 矩阵变换规则及圆形 ImageView 的实现与现代演进。

src 与 background 的核心差异及防变形技巧

`ImageView` 是展示位图与矢量图形的基础控件,支持通过 `android:src`(前景内容)和 `android:background`(背景层)两项属性加载图像。当宽高均为 `wrap_content` 时二者均呈现原图尺寸;一旦显式指定宽度或高度(如 `200dp`),`background` 会直接拉伸填满整个控件边界,而 `src` 则严格遵循 `scaleType` 规则(XML 默认值为 `fitCenter`),仅当宽高同时小于原图或缩放模式要求时才缩放内容。

为防止 `background` 拉伸变形,可采用两种方法:动态添加控件时直接以固定尺寸 `LayoutParams` 约束宽高;XML 布局中则可创建 `<bitmap>` Drawable 资源并设置 `android:tileMode="disabled"`(关闭平铺)与 `android:gravity`,再赋给 `background` 或调用 `setBackgroundResource()`。此外,`setAlpha()`(现行推荐 `setImageAlpha(int)`)仅作用于 `src` 前景图像;将透明底 PNG 作为 `src` 与纯色或 `<selector>` 作为 `background` 叠加,可低成本做出不规则图标与按压高亮效果;Java 代码中分别通过 `setImageDrawable()` 与 `setBackgroundDrawable()`(API 16+ 为 `setBackground()`)更新前景与背景。

adjustViewBounds 等比边界约束

设置 `android:adjustViewBounds="true"` 可让 `ImageView` 在调整自身边界时保持原图长宽比,但它单独配置不会生效,必须同时配合 `android:maxWidth`、`android:maxHeight`(且至少有一侧为 `wrap_content`)才能触发约束。本站实验实测原图在最大边界 `200x200px` 约束下的精确等比缩放:横向 `541x374` 约束为 `200x138`,纵向 `374x541` 约束为 `138x200`,而小于边界的 `100x80` 保持原尺寸不盲目放大。

scaleType 八种缩放模式矩阵解析

`android:scaleType`(Java 对应 `setScaleType(ImageView.ScaleType.*)`,注意 `ImageView` 默认值为 `fitCenter` 而非 `matrix`)提供 8 种标准变换策略:`fitXY` 独立拉伸宽高压满视图(会破坏纵横比,注意 XML 属性值须拼写为 `fitXY` 而非 `fixXY`);`fitStart`、`fitCenter`、`fitEnd` 均保持纵横比缩放至某一边贴合容器后分别靠左上、居中、靠右下放置;`center` 保持原图大小居中绘制,超出部分裁剪;`centerCrop` 等比放大或缩小至完全铺满容器并居中裁剪溢出边;`centerInside` 仅当原图大于容器时等比缩小至完整显示,原图更小时保持 1:1 居中不放大;`matrix` 则直接按变换矩阵从左上角绘制原图(默认单位矩阵不缩放,超出裁剪)。

本站离线矩阵模型针对 `400x200` 图像放入 `300x300` 容器完整求解了全部 8 种模式的缩放因子与目标绘制矩形:`fitXY` 产生非均匀缩放 `(sx=0.75, sy=1.5)`;`fitStart`/`fitCenter`/`fitEnd` 均为 `0.75` 等比缩放,纵向区间依次位于 `[0, 150]`、`[75, 225]`、`[150, 300]`;`centerCrop` 放大至 `1.5` 倍使水平绘制延伸至 `[-150, 450]` 覆盖全屏;而对 `100x50` 小图放入 `300x300` 容器时,`fitCenter` 会放大 `3.0` 倍,`centerInside` 则维持 `1.0` 倍原尺寸,清晰区分了两者的边界差异。

自定义圆形 ImageView 与现代工程替代

教学示例常通过继承 `ImageView` 编写简易 `RoundImageView` 演示圆形头像:在 `onDraw()` 中构造 `Path.addCircle(...)` 并调用 `canvas.clipPath(...)` 裁剪画布后再 `drawBitmap`。需提示三点工程注意事项:第一,示例中 `addCircle(getWidth()/2, getWidth()/2, getHeight()/2, ...)` 在非正方形容器下圆心纵坐标会偏离中心,应改为 `(getWidth()/2f, getHeight()/2f, Math.min(getWidth(), getHeight())/2f)`;第二,高版本 API 28 已废弃带 `Region.Op.REPLACE` 参数的 `clipPath`,且在 `onDraw` 中反复 `addCircle` 未 `reset` 会不断累积路径;第三,生产项目应优先选用 Material Components 的 `ShapeableImageView`、成熟图片库(Glide/Coil 圆形变换)或开源控件 `CircleImageView`/`RoundedImageView`。

运行离线 ImageView src/background、adjustViewBounds、8 种 ScaleType 矩阵与圆形裁剪核验

含完整源码 · 153 行
展开查看收起
python
"""Offline Android UI verifier for Ch 25: ImageView."""
import json
import xml.etree.ElementTree as ET

ANDROID_NS = "{http://schemas.android.com/apk/res/android}"

BITMAP_BG_XML = """<bitmap
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@id/pen_bg"
    android:gravity="top"
    android:src="@drawable/pen"
    android:tileMode="disabled" />
"""


def adjust_view_bounds(img_w: int, img_h: int, max_w: int, max_h: int) -> list:
    scale = min(1.0, max_w / img_w, max_h / img_h)
    return [int(round(img_w * scale)), int(round(img_h * scale))]


def compute_scale_type(mode: str, img_w: float, img_h: float, view_w: float, view_h: float) -> dict:
    if mode == "fitXY":
        return {"rect": [0.0, 0.0, view_w, view_h], "sx": round(view_w / img_w, 4), "sy": round(view_h / img_h, 4)}
    if mode in ("fitStart", "fitCenter", "fitEnd"):
        s = min(view_w / img_w, view_h / img_h)
        dw, dh = img_w * s, img_h * s
        if mode == "fitStart":
            x, y = 0.0, 0.0
        elif mode == "fitCenter":
            x, y = (view_w - dw) / 2.0, (view_h - dh) / 2.0
        else:
            x, y = view_w - dw, view_h - dh
        return {"rect": [round(x, 2), round(y, 2), round(x + dw, 2), round(y + dh, 2)], "sx": round(s, 4), "sy": round(s, 4)}
    if mode == "center":
        x, y = (view_w - img_w) / 2.0, (view_h - img_h) / 2.0
        return {"rect": [round(x, 2), round(y, 2), round(x + img_w, 2), round(y + img_h, 2)], "sx": 1.0, "sy": 1.0}
    if mode == "centerCrop":
        s = max(view_w / img_w, view_h / img_h)
        dw, dh = img_w * s, img_h * s
        x, y = (view_w - dw) / 2.0, (view_h - dh) / 2.0
        return {"rect": [round(x, 2), round(y, 2), round(x + dw, 2), round(y + dh, 2)], "sx": round(s, 4), "sy": round(s, 4)}
    if mode == "centerInside":
        s = 1.0 if (img_w <= view_w and img_h <= view_h) else min(view_w / img_w, view_h / img_h)
        dw, dh = img_w * s, img_h * s
        x, y = (view_w - dw) / 2.0, (view_h - dh) / 2.0
        return {"rect": [round(x, 2), round(y, 2), round(x + dw, 2), round(y + dh, 2)], "sx": round(s, 4), "sy": round(s, 4)}
    if mode == "matrix":
        return {"rect": [0.0, 0.0, img_w, img_h], "sx": 1.0, "sy": 1.0}
    raise ValueError(mode)


def main() -> None:
    bmp = ET.fromstring(BITMAP_BG_XML)
    c1_actual = {
        "bitmap_tile_mode": bmp.attrib[f"{ANDROID_NS}tileMode"],
        "bitmap_gravity": bmp.attrib[f"{ANDROID_NS}gravity"],
        "set_alpha_affects": "src_only",
        "background_fills_bounds": True,
        "default_xml_scaletype": "fitCenter",
    }
    c1_expected = {
        "bitmap_tile_mode": "disabled",
        "bitmap_gravity": "top",
        "set_alpha_affects": "src_only",
        "background_fills_bounds": True,
        "default_xml_scaletype": "fitCenter",
    }

    # Case 2: adjustViewBounds with maxWidth=200, maxHeight=200
    c2_actual = {
        "landscape_541x374": adjust_view_bounds(541, 374, 200, 200),
        "portrait_374x541": adjust_view_bounds(374, 541, 200, 200),
        "small_100x80_no_upscale": adjust_view_bounds(100, 80, 200, 200),
    }
    c2_expected = {
        "landscape_541x374": [200, 138],
        "portrait_374x541": [138, 200],
        "small_100x80_no_upscale": [100, 80],
    }

    # Case 3: All 8 ScaleType matrix transforms on 400x200 image in 300x300 view + small 100x50 comparison
    modes = ("fitXY", "fitStart", "fitCenter", "fitEnd", "center", "centerCrop", "centerInside", "matrix")
    c3_actual = {m: compute_scale_type(m, 400.0, 200.0, 300.0, 300.0) for m in modes}
    c3_actual["small_100x50_fitCenter_vs_centerInside"] = {
        "fitCenter_scale": compute_scale_type("fitCenter", 100.0, 50.0, 300.0, 300.0)["sx"],
        "centerInside_scale": compute_scale_type("centerInside", 100.0, 50.0, 300.0, 300.0)["sx"],
    }
    c3_expected = {
        "fitXY": {"rect": [0.0, 0.0, 300.0, 300.0], "sx": 0.75, "sy": 1.5},
        "fitStart": {"rect": [0.0, 0.0, 300.0, 150.0], "sx": 0.75, "sy": 0.75},
        "fitCenter": {"rect": [0.0, 75.0, 300.0, 225.0], "sx": 0.75, "sy": 0.75},
        "fitEnd": {"rect": [0.0, 150.0, 300.0, 300.0], "sx": 0.75, "sy": 0.75},
        "center": {"rect": [-50.0, 50.0, 350.0, 250.0], "sx": 1.0, "sy": 1.0},
        "centerCrop": {"rect": [-150.0, 0.0, 450.0, 300.0], "sx": 1.5, "sy": 1.5},
        "centerInside": {"rect": [0.0, 75.0, 300.0, 225.0], "sx": 0.75, "sy": 0.75},
        "matrix": {"rect": [0.0, 0.0, 400.0, 200.0], "sx": 1.0, "sy": 1.0},
        "small_100x50_fitCenter_vs_centerInside": {"fitCenter_scale": 3.0, "centerInside_scale": 1.0},
    }

    # Case 4: RoundImageView clip circle geometry (square vs non-square)
    def safe_circle(w: int, h: int) -> dict:
        return {"cx": w / 2.0, "cy": h / 2.0, "r": min(w, h) / 2.0}

    c4_actual = {
        "square_200x200": safe_circle(200, 200),
        "rect_200x100_safe": safe_circle(200, 100),
        "rect_200x100_naive_cy_outside_center": 200 / 2.0 != 100 / 2.0,
    }
    c4_expected = {
        "square_200x200": {"cx": 100.0, "cy": 100.0, "r": 100.0},
        "rect_200x100_safe": {"cx": 100.0, "cy": 50.0, "r": 50.0},
        "rect_200x100_naive_cy_outside_center": True,
    }

    cases = [
        {
            "name": "src_vs_background_and_bitmap_tilemode",
            "summary": "核对 ImageView 的 src/background 渲染差异、bitmap tileMode=disabled 与 setAlpha 作用范围",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "adjust_view_bounds_aspect_clamp",
            "summary": "计算 adjustViewBounds=true 配合 maxWidth/maxHeight=200px 时的等比约束尺寸",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "scaletype_eight_modes_matrix_math",
            "summary": "精确求解 ImageView 全部 8 种 ScaleType 的缩放系数与目标绘制矩形,并对比小图下 fitCenter 与 centerInside",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "round_imageview_clip_geometry",
            "summary": "验证自定义圆形 ImageView 的圆心与半径几何计算及非正方形容器的边界保护",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({
        "version": "CPython 3.12.14 offline Android UI/XML/Adapter verifier (Android SDK/emulator absent)",
        "cases": cases,
    }, ensure_ascii=False))


if __name__ == "__main__":
    main()
验证 bitmap tileMode=disabled、200px 等比边界约束、全部 8 种 ScaleType 精确绘制矩形及非正方形圆心修正。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1829.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1906.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

`fitCenter` 会将小图等比放大 `3` 倍至 `300x150` 居中铺满较长边;而 `centerInside` 在原图小于容器时保持 `1:1` 原尺寸(`100x50`)居中显示,不会放大图片。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习