自定义圆角的Relativelayout
Posted awkflf11
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自定义圆角的Relativelayout相关的知识,希望对你有一定的参考价值。
package com.ymw.sqlite.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.widget.RelativeLayout;
/**
* 自定义控件:圆角RelativeLayout
* 如果想改为圆形view,修改rect_adius为很大的数字,比如100
*/
public class RoundRelativeLayout extends RelativeLayout {
private final RectF roundRect = new RectF();
private final Paint maskPaint = new Paint();
private final Paint zonePaint = new Paint();
private Context mContext;
private float rect_adius = 8; //单位为像素
public RoundRelativeLayout(Context context) {
super(context);
init(context);
}
public RoundRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public RoundRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
this.mContext = context;
maskPaint.setAntiAlias(true);
maskPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
zonePaint.setAntiAlias(true);
zonePaint.setColor(Color.WHITE);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
int w = getWidth();
int h = getHeight();
roundRectSet(w, h);
}
@Override
public void draw(Canvas canvas) {
canvasSetLayer(canvas);
super.draw(canvas);
canvas.restore();
}
/**
* 从新设置圆角
*
* @param adius
*/
public void setRectAdius(float adius) {
rect_adius = adius;
invalidate();
}
/**
* 圆角区域设置
*
* @param width
* @param height
*/
private void roundRectSet(int width, int height) {
roundRect.set(0, 0, width, height);
}
/**
* 画布区域裁剪
*
* @param canvas
*/
private void canvasSetLayer(Canvas canvas) {
canvas.saveLayer(roundRect, zonePaint, Canvas.ALL_SAVE_FLAG);
canvas.drawRoundRect(roundRect, rect_adius, rect_adius, zonePaint);
//
canvas.saveLayer(roundRect, maskPaint, Canvas.ALL_SAVE_FLAG);
}
}
2.布局在xml文件中使用
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.ymw.sqlite.view.RoundRelativeLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
android:background="@drawable/test"
android:gravity="center">
<TextView
android:id="@+id/price"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:text="$200.11"
android:textColor="@color/white" />
</com.ymw.sqlite.view.RoundRelativeLayout>
</RelativeLayout>
以上是关于自定义圆角的Relativelayout的主要内容,如果未能解决你的问题,请参考以下文章
从自定义视图访问 RelativeLayout 时出现 NullPointerException