Skip to content

Instantly share code, notes, and snippets.

@Yellow5A5
Created December 12, 2017 17:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yellow5A5/a9593589ced2d9361ac9bd8daf6c36e9 to your computer and use it in GitHub Desktop.
Save Yellow5A5/a9593589ced2d9361ac9bd8daf6c36e9 to your computer and use it in GitHub Desktop.
Android-View
package com.yellow5a5.roundedcornerslayout;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
/**
* Created by Yellow5A5 on 2017/8/16.
* 可配圆角裁剪容器,直接外部包裹一层即可。
*/
public class RoundedCornersRLayout extends RelativeLayout {
private Path mPath;
private int mXcornor;
private int mYcornor;
private int mBorderColor;
private int mBorderSize;
private float mDensity;
private Paint mBorderPaint = new Paint();
public RoundedCornersRLayout(Context context) {
this(context, null);
}
public RoundedCornersRLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundedCornersRLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornersRLayout);
mXcornor = typedArray.getDimensionPixelSize(R.styleable.RoundedCornersRLayout_x_corners, 4);
mYcornor = typedArray.getDimensionPixelSize(R.styleable.RoundedCornersRLayout_y_corners, 4);
mBorderSize = typedArray.getDimensionPixelSize(R.styleable.RoundedCornersRLayout_border_width, 0);
mBorderColor = typedArray.getColor(R.styleable.RoundedCornersRLayout_border_color, -1);
mDensity = context.getResources().getDisplayMetrics().density;
mXcornor *= mDensity;
mYcornor *= mDensity;
setWillNotDraw(false);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
typedArray.recycle();
if(mBorderSize != 0 && mBorderColor != -1){
mBorderPaint.setAntiAlias(true);
mBorderPaint.setColor(mBorderColor);
mBorderPaint.setStrokeWidth(mBorderSize);
mBorderPaint.setStyle(Paint.Style.STROKE);
}
}
@Override
public void draw(Canvas canvas) {
if (mPath == null) {
mPath = new Path();
mPath.addRoundRect(new RectF(0, 0, getWidth(), getHeight()), mXcornor, mYcornor, Path.Direction.CW);
}
canvas.clipPath(mPath);
if(mBorderSize != 0 && mBorderColor != -1){
canvas.drawPath(mPath, mBorderPaint);
}
super.draw(canvas);
}
}
atts.xml
<resources>
<declare-styleable name="RoundedCornersRLayout">
<attr name="x_corners" format="dimension" />
<attr name="y_corners" format="dimension" />
<attr name="border_color" format="color" />
<attr name="border_width" format="dimension" />
</declare-styleable>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment