使用Android中的Path和RectF在左上角右上角左下角绘制圆角

时间:2017-02-01 17:35:24

标签: android imageview rounded-corners

通过创建custom ImageView并使用以下内容覆盖onDraw方法将使ImageView具有圆角。参考

@Override
protected void onDraw(Canvas canvas) {
    float radius = getContext().getResources().getDimension(R.dimen.round_corner_radius);
    Path path = new Path();
    RectF rect = new RectF(0, 0, this.getWidth(), this.getHeight());
    path.addRoundRect(rect, radius, radius, Path.Direction.CW);
    canvas.clipPath(path);
    super.onDraw(canvas);
}

如何选择性地制作圆角而不是使所有四个角都圆。例如,仅使左上角和右上角成圆形并保持底角完好无损。这是通过Bitmap执行的solution。我正在寻找在这个onDraw方法中只使用Path和RectF。

2 个答案:

答案 0 :(得分:22)

有一个Path#addRoundRect()重载需要float八个值的数组,其中我们可以为四个角中的每一个指定x和y半径。这些值为[x,y]对,从左上角开始,顺时针绕其余部分。对于那些我们想要舍入的角点,我们将该对的两个值都设置为半径值,并将它们保留为零,而不是那些。

作为一个说明性示例,一个简单的方法将返回可在您的代码段中使用的Path

private Path getPath(float radius, boolean topLeft, boolean topRight,
                     boolean bottomRight, boolean bottomLeft) {

    final Path path = new Path();
    final float[] radii = new float[8];

    if (topLeft) {
        radii[0] = radius;
        radii[1] = radius;
    }

    if (topRight) {
        radii[2] = radius;
        radii[3] = radius;
    }

    if (bottomRight) {
        radii[4] = radius;
        radii[5] = radius;
    }

    if (bottomLeft) {
        radii[6] = radius;
        radii[7] = radius;
    }

    path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()),
                      radii, Path.Direction.CW);

    return path;
}

根据您的示例说明,舍入左上角和右上角:

@Override
protected void onDraw(Canvas canvas) {
    float radius = getContext().getResources().getDimension(R.dimen.round_corner_radius);
    Path path = getPath(radius, true, true, false, false);
    canvas.clipPath(path);
    super.onDraw(canvas);
}

与往常一样,我建议尽可能地保持onDraw()方法,移动任何其他地方不必存在的东西。例如,可以在构造函数中检索radius的资源值,并将其保存在字段中。此外,Path只能在必要时构建;即,当View的尺寸发生变化时,或当半径或选定角落发生变化时。

由于我将一个简单的自定义ImageView放在一起进行测试,我会将其包含在此处,因为它演示了以上几点。此自定义View还提供XML属性,允许在布局中设置角半径和圆角。

public class RoundishImageView extends ImageView {

    public static final int CORNER_NONE = 0;
    public static final int CORNER_TOP_LEFT = 1;
    public static final int CORNER_TOP_RIGHT = 2;
    public static final int CORNER_BOTTOM_RIGHT = 4;
    public static final int CORNER_BOTTOM_LEFT = 8;
    public static final int CORNER_ALL = 15;

    private static final int[] CORNERS = {CORNER_TOP_LEFT,
                                          CORNER_TOP_RIGHT,
                                          CORNER_BOTTOM_RIGHT,
                                          CORNER_BOTTOM_LEFT};

    private final Path path = new Path();
    private int cornerRadius;
    private int roundedCorners;

    public RoundishImageView(Context context) {
        this(context, null);
    }

    public RoundishImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundishImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundishImageView);
        cornerRadius = a.getDimensionPixelSize(R.styleable.RoundishImageView_cornerRadius, 0);
        roundedCorners = a.getInt(R.styleable.RoundishImageView_roundedCorners, CORNER_NONE);
        a.recycle();
    }

    public void setCornerRadius(int radius) {
        if (cornerRadius != radius) {
            cornerRadius = radius;
            setPath();
            invalidate();
        }
    }

    public int getCornerRadius() {
        return cornerRadius;
    }

    public void setRoundedCorners(int corners) {
        if (roundedCorners != corners) {
            roundedCorners = corners;
            setPath();
            invalidate();
        }
    }

    public boolean isCornerRounded(int corner) {
        return (roundedCorners & corner) == corner;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (!path.isEmpty()) {
            canvas.clipPath(path);
        }

        super.onDraw(canvas);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        setPath();
    }

    private void setPath() {
        path.rewind();

        if (cornerRadius >= 1f && roundedCorners != CORNER_NONE) {
            final float[] radii = new float[8];

            for (int i = 0; i < 4; i++) {
                if (isCornerRounded(CORNERS[i])) {
                    radii[2 * i] = cornerRadius;
                    radii[2 * i + 1] = cornerRadius;
                }
            }

            path.addRoundRect(new RectF(0, 0, getWidth(), getHeight()),
                              radii, Path.Direction.CW);
        }
    }
}

要使XML属性起作用,需要在<resources>中使用以下内容,您可以将此文件放在项目的res/values/文件夹中,或添加到可能已存在的文件中。那里。

attrs.xml

<resources>
    <declare-styleable name="RoundishImageView">
        <attr name="cornerRadius" format="dimension" />
        <attr name="roundedCorners">
            <flag name="topLeft" value="1" />
            <flag name="topRight" value="2" />
            <flag name="bottomRight" value="4" />
            <flag name="bottomLeft" value="8" />
            <flag name="all" value="15" />
        </attr>
    </declare-styleable>
</resources>

cornerRadius是维度属性,应指定为dppx值。 roundedCorners是一个标志属性,可以使用竖线字符|选择多个角。例如:

<com.mycompany.myapp.RoundishImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/riv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    android:src="@drawable/magritte"
    app:cornerRadius="@dimen/round_corner_radius"
    app:roundedCorners="topLeft|topRight" />

screenshot

答案 1 :(得分:0)

我也花了半天时间来解决问题;这里的关键点是如何使用mPath.arcTo开一个角。基本知识是E方向为0度,则第二个参数表示从哪个角度开始;第三个参数表示要显示多少度。

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.DecelerateInterpolator;

public class RectangleConerView extends View {

private Path mPath;
private Paint mPaint;
private PathMeasure mPathMeasure;
private float mAnimatorValue;
private Path mDst;
private float mLength;

private float left = 300;
private float top = 200;

private float width = 800;
private float height = 300;
private float checkWidth = 100;
private float checkHeight = 60;
private float cornerRadius = 30;

public RectangleConerView(Context context) {
    super(context);
}

public RectangleConerView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
}

public RectangleConerView(Context context, AttributeSet attrs) 
{
    super(context, attrs);
    mPathMeasure = new PathMeasure();
    mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeWidth(5);
    mPath = new Path();

    mPath.moveTo(left + width, top + checkHeight/2);

    //bottom-right
    mPath.lineTo(left + width, top + height - cornerRadius);
    mPath.arcTo(new RectF(left + width-cornerRadius, top + height - cornerRadius, left + width, top + height), 0, 90); //start degree is E direct, then CW 90 degree, which is the bottom-right corner.

    //bottom-left
    mPath.lineTo(left + cornerRadius, top + height);
    mPath.arcTo(new RectF(left, top + height - cornerRadius, left + cornerRadius, top + height), 90, 90);//start degree is the S, then CW 90 degree, which is the bottom-left corner.

    //top-left
    mPath.lineTo(left, top + cornerRadius);
    mPath.arcTo(new RectF(left, top, left + cornerRadius, top + cornerRadius), 180, 90);//start degree W

    //top-right
    mPath.lineTo(left + width - checkWidth/2, top);


    mPathMeasure.setPath(mPath, false);
    mLength = mPathMeasure.getLength();
    mDst = new Path();

    final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            mAnimatorValue = (float) valueAnimator.getAnimatedValue();
            invalidate();
        }
    });
    valueAnimator.setDuration(1000);
    valueAnimator.setRepeatCount(ValueAnimator.INFINITE);
    valueAnimator.setInterpolator(new DecelerateInterpolator());

    valueAnimator.start();
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    mDst.reset();
    // 硬件加速的BUG
    mDst.lineTo(0,0);
    float stop = mLength * mAnimatorValue;
    mPathMeasure.getSegment(0, stop, mDst, true);
    canvas.drawPath(mDst, mPaint);
}
}

enter image description here