在搜索了很多之后,我真的在网上找不到任何东西。所以我试着从头开始画。这并不完美,所以我以后会努力让它变得更好。你需要做一些三角数学来画一些扇区。然后使用渐变创建淡出效果。
这是我的代码:
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
public class SpotLightsView extends View {
private static final String TAG = SpotLightsView.class.getSimpleName();
private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
private double angleDegree = 10;
private double angleRadian = Math.toRadians(angleDegree);
private final double dTheta = angleRadian;
private double WIDTH = 100;
private double HEIGHT = 100;
private double RADIUS = (1.4142*WIDTH/2); // r = a*sqrt(2);
private double cx = WIDTH/2;
private double cy = HEIGHT/2;
public SpotLightsView(Context context) {
super(context);
}
public SpotLightsView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public SpotLightsView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
WIDTH = canvas.getWidth();
HEIGHT = canvas.getHeight();
cx = WIDTH/2;
cy = HEIGHT/2;
RADIUS = cy*1.4142; // r = a*sqrt(2);
drawSpotLights(canvas);
}
private void drawSpotLights(Canvas canvas) {
double theta = 0;
for(int i=0; i<360/angleDegree; i++){
drawSpotLightOn(canvas, theta);
theta+=dTheta;
}
}
private void drawSpotLightOn(Canvas canvas, double theta){
double x1, y1, x2, y2, x3, y3, sinTheta, cosTheta;
double r = 50;
sinTheta = Math.sin(theta);
cosTheta = Math.cos(theta);
x1 = cx + RADIUS*cosTheta;
y1 = cy + RADIUS*sinTheta;
x2 = x1 + r*sinTheta;
y2 = y1 - r*cosTheta;
x3 = x1 - r*sinTheta;
y3 = y1 + r*cosTheta;
LinearGradient linearGradient = new LinearGradient((float)cx,(float)cy,(float)x1,(float)y1, 0x88ffffff,
0x00000000, android.graphics.Shader.TileMode.CLAMP);
mPaint.setDither(true);
mPaint.setShader(linearGradient);
mPaint.setStyle(Paint.Style.FILL);
Path path = new Path();
path.moveTo((float)cx, (float)cy);
path.lineTo((float)x3, (float)y3);
path.quadTo((float)x1, (float)y1, (float)x2, (float)y2);
path.lineTo((float)cx, (float)cy);
canvas.drawPath(path, mPaint);
}
}
然后像这样在你的
some_layout.xml
文件:
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
输出如下:
简短的解释
改变
private double angleDegree = 10;
来说明你想要聚光灯的度数。
然后我们在for循环中增加角度并调用
private void drawSpotLightOn(Canvas canvas, double theta)
方法。在第二行,有一个值
double r=50
. 它告诉代码弧在终点处的宽度。更改这2个并查看结果以获得所需的输出。
为了使淡出效果,我用
LinearGradient
其余的代码都是直截了当的。你可以在任何安卓系统中找到它们
Paint
,
CustomView
教程。