在Android中,要實現自定義形狀的SweepGradient漸變,你需要遵循以下步驟:
CustomShapeDrawable.java
的文件,并繼承自Drawable
類。然后重寫onDraw()
方法來繪制你的形狀。import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
public class CustomShapeDrawable extends Drawable {
private Path path;
private Paint paint;
public CustomShapeDrawable(Context context) {
path = new Path();
paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(5);
paint.setStyle(Paint.Style.STROKE);
}
public void setShape(Path shape) {
path.reset();
path.addPath(shape);
}
@Override
protected void onBoundsChange(RectF bounds) {
super.onBoundsChange(bounds);
if (!path.isEmpty()) {
path.setBounds(bounds);
}
}
@Override
public void draw(@NonNull Canvas canvas) {
canvas.drawPath(path, paint);
}
@Override
public void setColorFilter(@Nullable PorterDuffColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return paint.getAlpha();
}
}
CustomShapeDrawable
作為背景。例如,創建一個名為activity_main.xml
的文件,并在LinearLayout
中使用CustomShapeDrawable
:<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/custom_shape">
<!-- 其他視圖 -->
</LinearLayout>
</LinearLayout>
Path
對象,定義你的自定義形狀,并將其設置為CustomShapeDrawable
的背景。例如,在MainActivity.java
文件中:import android.graphics.Path;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = findViewById(R.id.linearLayout);
Path path = new Path();
path.moveTo(50, 50);
path.lineTo(200, 50);
path.lineTo(150, 200);
path.close();
CustomShapeDrawable customShapeDrawable = new CustomShapeDrawable(this);
customShapeDrawable.setShape(path);
customShapeDrawable.setStrokeColor(Color.BLUE);
customShapeDrawable.setFillColor(Color.GREEN);
linearLayout.setBackground(customShapeDrawable);
}
}
現在,你的自定義形狀將作為SweepGradient漸變背景顯示在布局中。你可以根據需要調整形狀的坐標、顏色和其他屬性。