Android改造CardView为圆形View,Kotlin

Android改造CardView为圆形View,Kotlin

可以利用androidx.cardview.widget.CardView的cardCornerRadius特性,将CardView改造成一个圆形的View,技术实现的关键首先设定CardView为一个宽高相等的View(正方形),然后将radius特意设置成宽度(或高度,一样,因为正方形,宽高相等)的1/2,此时CardView自然就变成一个圆。

(1)kotlin代码运行时生成:

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val circularCardView = CircularCardView(this)
        circularCardView.setCardBackgroundColor(Color.BLUE)
        setContentView(circularCardView)
    }
}

class CircularCardView(ctx: Context) : CardView(ctx) {
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val width = measuredWidth
        setMeasuredDimension(width, width)
        radius = (width / 2).toFloat()
    }
}

(2)在xml布局中实现:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.cardview.widget.CardView
        android:layout_width="200dp"
        android:layout_height="200dp"
        app:cardBackgroundColor="@android:color/holo_orange_light"
        app:cardCornerRadius="100dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.widget.ConstraintLayout>

Android RoundedBitmapDrawable:Android官方的圆角图形图象实现方案_android 官方圆角-CSDN博客Android RoundedBitmapDrawable:Android官方的圆角图形图象实现方案RoundedBitmapDrawable是Android在support v4的扩展包中新增的实现圆角图形的关键类,借助RoundedBitmapDrawable的帮助,可以轻松的以Android标准方式实现圆角图形图象。写一个简单的例子。写一个线性布局,竖直方向放三个Im_android 官方圆角https://blog.csdn.net/zhangphil/article/details/51829650Android CardView设置成普通的Framelayout-CSDN博客比如可以这样写代码,CardView就变成普通的FrameLayout:https://blog.csdn.net/zhangphil/article/details/52911922

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值