xml 仅缩放视图内容的ViewGroup - 实际测量的尺寸保持不变
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了xml 仅缩放视图内容的ViewGroup - 实际测量的尺寸保持不变相关的知识,希望对你有一定的参考价值。
package de.jskierbi.commons.ui
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
import de.neofonie.meinwerder.R
/**
* Created by jakub on 10.10.17.
*/
class ContentScaleView @JvmOverloads constructor(context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : ViewGroup(context, attrs, defStyleAttr) {
private val contentScale: Float
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.ContentScaleView, defStyleAttr, 0)
contentScale = a.getFloat(R.styleable.ContentScaleView_contentScale, 1f)
a.recycle()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
val contentWidth = (measuredWidth / contentScale).toInt()
val contentHeight = (measuredHeight / contentScale).toInt()
val childWidthSpec = MeasureSpec.makeMeasureSpec(contentWidth, MeasureSpec.EXACTLY)
val childHeightSpec = MeasureSpec.makeMeasureSpec(contentHeight, MeasureSpec.EXACTLY)
(0 until childCount).forEach {
val child = getChildAt(it)
child.measure(childWidthSpec, childHeightSpec)
child.scaleX = contentScale
child.scaleY = contentScale
}
}
override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
if (!changed) return
val width = (right - left)
val height = (bottom - top)
val expectedWidth = width / contentScale
val expectedHeight = height / contentScale
val widthDiff = ((expectedWidth - width) / 2).toInt()
val heightDiff = ((expectedHeight - height) / 2).toInt()
(0 until childCount).forEach {
val child = getChildAt(it)
child.layout(
0 - widthDiff,
0 - heightDiff,
width + widthDiff,
height + heightDiff
)
}
}
}
</resources>
<attr name="contentScale" format="float" />
<declare-styleable name="ContentScaleView">
<attr name="contentScale" />
</declare-styleable>
</resources>
以上是关于xml 仅缩放视图内容的ViewGroup - 实际测量的尺寸保持不变的主要内容,如果未能解决你的问题,请参考以下文章
安卓程序开发01
如何在图像视图中仅缩放可见图像而不是图像的透明部分?
android: 一个新的 GUI 问题 - 如何声明 viewGroup,没有布局 XML 文件?
视图组 (ViewGroup)中子元素的出场效果
动画视图仅缩放屏幕宽度的一半
Android围绕动态枢轴旋转视图