You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中ImageView的setImageMatrix无法生效问题求助

问题原因

你的sun drawable是shape类型,它没有固有宽高(intrinsic width/height)——这类矢量形状默认没有固定的尺寸属性。而ImageView的matrix变换是基于Drawable的固有尺寸计算的,当固有尺寸为0时,任何缩放、平移操作都不会产生视觉效果。

解决方案

方法1:给Shape添加固有尺寸

直接在shape的XML中添加<size>标签,指定它的宽高:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="@color/bright_sun" />
    <!-- 添加固定尺寸 -->
    <size android:width="100dp" android:height="100dp" />
</shape>

方法2:代码中手动设置Drawable边界

在设置Matrix前,给Drawable绑定和ImageView一致的边界尺寸,让变换有基准:

// 确保View已经完成测量,比如在点击事件或者post回调中执行
binding.sun.post {
    val drawable = binding.sun.drawable ?: return@post
    // 给Drawable设置和ImageView相同的边界
    drawable.setBounds(0, 0, binding.sun.width, binding.sun.height)
    
    val m = Matrix()
    // 缩放0.5倍示例
    m.setScale(0.5f, 0.5f)
    // 如果要水平镜像,用下面两行:
    // m.setScale(-1f, 1f)
    // m.postTranslate(binding.sun.width.toFloat(), 0f) // 平移修正位置,避免图像移出View
    
    binding.sun.imageMatrix = m
}

方法3:改用BitmapDrawable

将shape转换为Bitmap使用,BitmapDrawable自带固有尺寸,变换会正常生效:

binding.sun.post {
    // 创建对应尺寸的Bitmap
    val bitmap = Bitmap.createBitmap(binding.sun.width, binding.sun.height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    // 绘制shape到Bitmap
    binding.sun.drawable?.apply {
        setBounds(0, 0, bitmap.width, bitmap.height)
        draw(canvas)
    }
    // 设置Bitmap给ImageView
    binding.sun.setImageBitmap(bitmap)
    
    // 现在可以正常设置Matrix
    val m = Matrix()
    m.setScale(0.5f, 0.5f)
    binding.sun.imageMatrix = m
}
额外注意事项
  • 不要在onPreDraw中重复设置Matrix,该方法会频繁触发,建议在View初始化完成后(比如post回调、点击事件)执行变换逻辑。
  • 调用setImageMatrix后无需手动调用invalidate(),该方法内部会自动触发重绘。

内容的提问来源于stack exchange,提问作者Rokata

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 05:52:42