在Android中,自定義ProgressDrawable的形狀可以通過創建一個新的類并繼承自ProgressDrawable來實現。以下是一個簡單的示例,展示了如何創建一個帶有自定義形狀的ProgressDrawable:
import android.graphics.Canvas;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Build;
public class CustomProgressDrawable extends Drawable {
private Paint paint;
public CustomProgressDrawable() {
paint = new Paint();
paint.setAntiAlias(true);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(10);
}
@Override
protected void onBoundsChange(Rect bounds) {
super.onBoundsChange(bounds);
}
@Override
public void draw(Canvas canvas) {
// 在這里繪制你的自定義形狀
Rect bounds = getBounds();
int centerX = bounds.centerX();
int centerY = bounds.centerY();
int radius = Math.min(centerX, centerY) - (int) paint.getStrokeWidth() / 2;
paint.setColor(0xFF009688);
canvas.drawCircle(centerX, centerY, radius, paint);
paint.setColor(0xFFFF5722);
canvas.drawArc(bounds.left, bounds.top, bounds.right, bounds.bottom, 270, 120, false, paint);
}
@Override
public void setAlpha(int alpha) {
paint.setAlpha(alpha);
}
@Override
public void setColorFilter(ColorFilter colorFilter) {
paint.setColorFilter(colorFilter);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="false"
android:max="100"
android:progress="50" />
ProgressBar progressBar = findViewById(R.id.progressBar);
CustomProgressDrawable customProgressDrawable = new CustomProgressDrawable();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
progressBar.setProgressDrawable(customProgressDrawable);
} else {
progressBar.setIndeterminateDrawable(customProgressDrawable);
}
這樣,你就可以看到一個帶有自定義形狀的ProgressBar了。你可以根據需要修改CustomProgressDrawable
類中的draw()
方法,以繪制你想要的形狀。