我正在尝试在我的应用中创建以下设计。
它叠加在主 UI 之上。尝试使用主 UI 顶部的布局来创建它,其背景是在 XML 中创建的半透明形状。但是,即使阅读了多篇文章,我也无法弄清楚。
我尝试了以下方法,但没有用。创建了一个具有 200dp 描边的环形并将其设置为 imageview 的源,然后将 scaletype 设置为 centerCrop 但该形状不像位图那样缩放。
形状 XML:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="2"
android:useLevel="false" >
<solid android:color="@android:color/transparent" />
<stroke
android:width="200dp"
android:color="#80000000" />
</shape>
叠加布局:
<?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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/onboarding_background"
android:scaleType="centerCrop"/>
</RelativeLayout>
有关如何执行此操作或代码的任何指示都会非常有帮助。
最佳答案
我最近一直在玩类似的东西,并为你改编了它。 所有的魔法都发生在 onDraw 中:
public class FocusView extends View {
private Paint mTransparentPaint;
private Paint mSemiBlackPaint;
private Path mPath = new Path();
public FocusView(Context context) {
super(context);
initPaints();
}
public FocusView(Context context, AttributeSet attrs) {
super(context, attrs);
initPaints();
}
public FocusView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initPaints();
}
private void initPaints() {
mTransparentPaint = new Paint();
mTransparentPaint.setColor(Color.TRANSPARENT);
mTransparentPaint.setStrokeWidth(10);
mSemiBlackPaint = new Paint();
mSemiBlackPaint.setColor(Color.TRANSPARENT);
mSemiBlackPaint.setStrokeWidth(10);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPath.reset();
mPath.addCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 550, Path.Direction.CW);
mPath.setFillType(Path.FillType.INVERSE_EVEN_ODD);
canvas.drawCircle(canvas.getWidth() / 2, canvas.getHeight() / 2, 550, mTransparentPaint);
canvas.drawPath(mPath, mSemiBlackPaint);
canvas.clipPath(mPath);
canvas.drawColor(Color.parseColor("#A6000000"));
}
}
这里的技巧是创建一个Path(透明圆圈),这样我们就可以将路径的绘制方法设置为“路径外”而不是“路径内”。最后,我们可以简单地将 Canvas 剪裁到该路径,并填充黑色。
对于您来说,您只需将 Color.BLACK
更改为您的颜色,并更改所需的半径。
编辑:
哦,只需以编程方式添加它:
FocusView view = new FocusView(context)
your_layout.addView( View )
或通过 XML:
<package_path_to_.FocusView
android:layout_width="match_parent"
android:layout_height="match_parent" />
EDIT2:我刚刚看到您想要这个来启动您的应用程序。 您可以考虑看看 https://github.com/iammert/MaterialIntroView然后
关于android - 如何在 Android 的 XML 中创建 'transparent circle inside rectangle' 形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763696/