先上朋友给我看的图:
左边的是4.4.2版本以上的,右边的是4.4.2版本,问题很明显,半圆形的背景在4.4.2上面被拉伸。
这类问题以前也做过,脑子不记事,忘得快。但是我相信勤能补拙,赶紧的记个笔记吧。
我朋友用shape来实现这种效果的:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#CCCCCC"/>
<corners
android:bottomLeftRadius="0px"
android:bottomRightRadius="300dp"
android:topLeftRadius="0px"
android:topRightRadius="300dp"/>
</shape>
新建个Activity看看是不是版本的问题,布局文件:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="rongyun.tianxiabuyi.com.myapplication.MainActivity"
>
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:paddingRight="20dp"
android:textSize="18sp"
android:background="@drawable/view_semicircle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</android.support.constraint.ConstraintLayout>
分别在7.0和4.2上运行:
看来真的是和版本有关啊。操作的第一步总是先问度娘,度娘说我母鸡啊。后来各种 操作后,发现吧 android:bottomRightRadius=”300dp”和 android:topRightRadius=”300dp”设置小一点就行了,比如30dp,看看效果:
完美啊,于是猜测:在4.4.2及其以下版本,设置bottomRightRadius和topRightRadius的高度是控件高度的一半,就不会存在被拉伸的问题了。
开始我的验证:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 在视图绘制时调用该监听事件,会被调用多次,需要及时移除
text.viewTreeObserver.addOnPreDrawListener(object : ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
// 移除改监听
text.viewTreeObserver.removeOnPreDrawListener(this)
// 获取控件一半高度
var height = text.height / 2
// 获取控件背景并转为GradientDrawable对象
var gd=text.background as GradientDrawable
// 设置GradientDrawable的的corner, 1、2两个参数表示左上角,3、4表示右上角,5、6表示右下角,7、8表示左下角
gd.cornerRadii = floatArrayOf(0f, 0f,
height.toFloat(), height.toFloat(),
height.toFloat(), height.toFloat(),
0f, 0f)
return true
}
})
}
运行后的效果,问题解决啦。只是4.2版本的问题究竟出在哪,还求告知。