Android 实现圆弧背景(Shape实现和自定义View)

一、背景

如今Android系统的App,很多时候为了有更好的用户体验,都会有各种好看的UI,动画,点击效果等等,其中圆弧的控件在App中很常见,今儿就自己总结下自己实现圆弧的两种基础的方法。即Shape方法和使用View里面的方法自己画。

二、Shape属性

shape:即形状的意思,这是一种在 xml文件中定义的通用形状。

文件位置:res / drawable / 文件名.xml

代码:一个TextView的背景

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <padding
        android:bottom="8dp"
        android:left="24dp"
        android:right="24dp"
        android:top="8dp"/>
    <solid android:color="#ef7300" />
    <corners android:radius="12dp" />
</shape>

展示:

这样实现起来非常简单!但是需求有时候又很离谱,我们开发又必须做,这时候就得老老实实代码去实现。

关于Shape的属性介绍:可以看Android shape的用法详解_&岁月不待人&的博客-CSDN博客_android shape一、什么是Shape属性在项目中经常会给控件定义背景,有时候有些界面可以叫UI做好,但如何显示的更加的贴近用户,则需要我们客户端去优化。如果在设置背景Android:background=“图片、颜色”,设置单一的属性并不能带来更好的体验。我们此时就可以使用shape属性作为控件的背景。shape怎么弄?1. 在res/drawable下新建一个xml文件;2. 在代码中引用这个xml文件,引用方式和图片一样。shape有哪些功能?corners ———-圆角gradihttps://blog.csdn.net/LoveFHM/article/details/109508798

三、使用ViewGroup的onDraw或者dispatchDraw实现自定义View

需求:IM的聊天气泡绘制,1、指定的位置的弧度角,2、当为群主时,会给聊天气泡加上金边。

实现原理:众所周知,View是Android所有控件的基类,常用的TextView和ImageView是继承自VIew。ViewGroup是View的组合,它可以包含很多View以及ViewGroup,所以可以直接重写onDraw或者dispatchDraw来自定义View。主要就是使用canvas,paint,path这些东西来实现。

核心代码:

    private fun drawBackGround(context: Context, canvas: Canvas, data: ImMsgIn, width: Int, height: Int, chatType: Int) {
        val mBgColorOrigin = ContextCompat.getColor(context, R.color.im_msg_bg_origin)
        isSelfMessage = data.getSelfUserId() == data.getSenderId()//是自己的消息
        isOwner = data.getSenderId() == data.getOwnerId()//是否是群主
        val path = Path()
        paint.strokeWidth = 1f
        paint.style = Paint.Style.FILL
        paint.color = setColor(context, data, chatType)
        if (isSelfMessage) { //发送者为自己,统一为圆弧背景,无金边
            val rectF = RectF(0f, 0f, width.toFloat(), height.toFloat())
            val radii = floatArrayOf(dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 0f), dpToPx(context, 0f), dpToPx(context, 8f), dpToPx(context, 8f))//右下为直角,其他角弧度为8
            path.addRoundRect(rectF, radii, Path.Direction.CW)
            canvas.drawPath(path, paint)
        } else {
            paint.style = Paint.Style.FILL
            val rectF = RectF(0f, 0f, width.toFloat(), height.toFloat())
            val radii = floatArrayOf(dpToPx(context, 0f), dpToPx(context, 0f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f))
            path.addRoundRect(rectF, radii, Path.Direction.CW)
            canvas.drawPath(path, paint)
            isOwnerReplyQuestionIsPublic = true
            if (data.getReplyMsgQuestionIsPublished() != null) isOwnerReplyQuestionIsPublic = data.getReplyMsgQuestionIsPublished() == true
            if (isOwner && (isOwnerReplyQuestionIsPublic || chatType == UiMsgType.PRIVATE_CHAT)) {
                paint.strokeWidth = 1f
                paint.color = mBgColorOrigin
                paint.style = Paint.Style.STROKE //画金色边框
                canvas.drawPath(drawRect(context, width, height), paint)
            } else if (data.getUiTypeWithMessageType() == UiMsgType.MSG_TYPE_QUESTION && data.getQuestionStatus() == 0 && data.getPublished()) {
                paint.strokeWidth = 1f
                paint.color = mBgColorOrigin
                paint.style = Paint.Style.STROKE
                canvas.drawPath(drawRect(context, width, height), paint)
            }
        }
    }

  //金色边框
    private fun drawRect(context: Context, width: Int, height: Int): Path {
        val path = Path()
        val rectF = RectF(0.5f, 0.5f, width.toFloat() - 0.5f, height.toFloat() - 0.5f)
        val radii = floatArrayOf(dpToPx(context, 0f), dpToPx(context, 0f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f), dpToPx(context, 8f))
        path.addRoundRect(rectF, radii, Path.Direction.CW)
        return path
    }
    
    private fun dpToPx(context: Context, dipValue: Float): Float {
        val scale = context.applicationContext.resources.displayMetrics.density
        return dipValue * scale + 0.5f
    }

其实,这个金边吧,其实也可以通过xml文件里叠加View的层级来实现,不过写代码,也可以实现更多的需求

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
实现圆弧进度条的自定义ProgressBar,可以使用Canvas和Paint来绘制。 首先,创建一个自定义的ProgressBar类,继承自ProgressBar类,并实现构造方法和onDraw方法: ``` public class CircleProgressBar extends ProgressBar { private Paint paint; // 画笔 private int roundColor; // 圆环颜色 private int progressColor; // 进度条颜色 private int textColor; // 文字颜色 private float textSize; // 文字大小 private float roundWidth; // 圆环宽度 private int max; // 最大进度 private boolean textIsDisplayable; // 是否显示进度文字 private int style; // 进度条样式 public static final int STROKE = 0; public static final int FILL = 1; public CircleProgressBar(Context context) { this(context, null); } public CircleProgressBar(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CircleProgressBar(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // 获取自定义属性的值 TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.CircleProgressBar); roundColor = mTypedArray.getColor(R.styleable.CircleProgressBar_roundColor, Color.RED); progressColor = mTypedArray.getColor(R.styleable.CircleProgressBar_progressColor, Color.GREEN); textColor = mTypedArray.getColor(R.styleable.CircleProgressBar_textColor, Color.GREEN); textSize = mTypedArray.getDimension(R.styleable.CircleProgressBar_textSize, 15); roundWidth = mTypedArray.getDimension(R.styleable.CircleProgressBar_roundWidth, 5); max = mTypedArray.getInteger(R.styleable.CircleProgressBar_max, 100); textIsDisplayable = mTypedArray.getBoolean(R.styleable.CircleProgressBar_textIsDisplayable, true); style = mTypedArray.getInt(R.styleable.CircleProgressBar_style, 0); mTypedArray.recycle(); // 初始化画笔 paint = new Paint(); } @Override protected synchronized void onDraw(Canvas canvas) { super.onDraw(canvas); // 获取圆心坐标和半径 int centerX = getWidth() / 2; int centerY = getHeight() / 2; int radius = (int) (centerX - roundWidth / 2); // 绘制圆环 paint.setColor(roundColor); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(roundWidth); paint.setAntiAlias(true); canvas.drawCircle(centerX, centerY, radius, paint); // 绘制进度条 paint.setStrokeWidth(roundWidth); paint.setColor(progressColor); RectF oval = new RectF(centerX - radius, centerY - radius, centerX + radius, centerY + radius); switch (style) { case STROKE: paint.setStyle(Paint.Style.STROKE); canvas.drawArc(oval, 0, 360 * getProgress() / getMax(), false, paint); break; case FILL: paint.setStyle(Paint.Style.FILL_AND_STROKE); if (getProgress() != 0) canvas.drawArc(oval, 0, 360 * getProgress() / getMax(), true, paint); break; } // 绘制文字 paint.setStrokeWidth(0); paint.setColor(textColor); paint.setTextSize(textSize); paint.setTypeface(Typeface.DEFAULT_BOLD); int percent = (int) (((float) getProgress() / (float) getMax()) * 100); if (textIsDisplayable && percent >= 0) { String text = percent + "%"; float textWidth = paint.measureText(text); canvas.drawText(text, centerX - textWidth / 2, centerY + textSize / 2, paint); } } } ``` 在这个类中,我们定义了几个自定义属性,包括圆环颜色、进度条颜色、文字颜色、文字大小、圆环宽度、最大进度、是否显示进度文字、进度条样式等。在构造方法中,我们获取了这些属性的值,并初始化了画笔。在onDraw方法中,我们首先获取了圆心坐标和半径,然后使用画笔绘制了圆环和进度条,最后绘制了进度文字。 接下来,在布局文件中使用这个自定义ProgressBar: ``` <com.example.circleprogressbar.CircleProgressBar android:id="@+id/circle_progressbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" app:roundColor="#cccccc" app:roundWidth="5dp" app:progressColor="#FF4081" app:textColor="#FF4081" app:textSize="20sp" app:textIsDisplayable="true" app:style="STROKE" /> ``` 最后,在Java代码中设置进度值即可: ``` CircleProgressBar circleProgressBar = findViewById(R.id.circle_progressbar); circleProgressBar.setProgress(50); // 设置进度为50% ``` 这样就完成了自定义圆弧进度条的实现
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

&岁月不待人&

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

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

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

打赏作者

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

抵扣说明:

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

余额充值