我正在嘗試用破折號創建一個可繪制的圓圈。我能夠用破折號實作圓圈,但無法應用漸變色。有什么辦法嗎?提前致謝。
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="@dimen/size60"
android:height="@dimen/size60" />
<stroke
android:width="1dp"
android:color="@color/white"
android:dashWidth="3dp"
android:dashGap="1dp" />
</shape>
實作的視圖:

需要查看:

uj5u.com熱心網友回復:
沒有辦法僅使用 XML AFAIK 創建漸變環。使用自定義可繪制物件會更好。下面將掃描漸變著色器與Paint物件結合起來,創建一個從頭到尾具有漸變的環。
class DashedRingDrawable : Drawable() {
private val mPaint = Paint().apply {
style = Paint.Style.STROKE
strokeWidth = STROKE_WIDTH
}
private val mColorArray = intArrayOf(Color.WHITE, Color.BLACK)
private var mRingOuterDiameter = 0f
private var mRingOuterRadius = 0f
private var mRingInnerRadius = 0f
override fun onBoundsChange(bounds: Rect) {
super.onBoundsChange(bounds)
check(bounds.width() == bounds.height()) {
"Width must be equal to height. (It's a circle.)"
}
mRingOuterDiameter = bounds.width().toFloat()
mRingOuterRadius = mRingOuterDiameter / 2
mRingInnerRadius = (mRingOuterDiameter - STROKE_WIDTH) / 2
val dashLength = getNewDashLength()
mPaint.pathEffect = DashPathEffect(floatArrayOf(dashLength, GAP_LENGTH), 0f)
mPaint.shader = SweepGradient(mRingOuterRadius, mRingOuterRadius, mColorArray, null)
}
override fun draw(canvas: Canvas) {
// The following statement is here to show the boundaries and can be removed/commented out.
// canvas.drawColor(Color.RED)
canvas.drawCircle(mRingOuterRadius, mRingOuterRadius, mRingInnerRadius, mPaint)
}
override fun setAlpha(alpha: Int) {
}
override fun setColorFilter(colorFilter: ColorFilter?) {
}
override fun getOpacity(): Int {
return PixelFormat.OPAQUE
}
// Adjust the dash length so that we end on a gap and not in the middle of a dash.
private fun getNewDashLength(): Float {
val circumference = Math.PI.toFloat() * mRingInnerRadius
val dashCount = (circumference / (DASH_LENGTH GAP_LENGTH)).toInt()
val newDashLength = (circumference - dashCount * GAP_LENGTH) / dashCount
return newDashLength
}
companion object {
const val STROKE_WIDTH = 15f
const val DASH_LENGTH = 50f
const val GAP_LENGTH = 15f
}
}

對于 API 24 及更高版本,您可以將此可繪制物件放入 XML 檔案中,并像使用任何其他 XML 可繪制物件一樣使用它。
<drawable xmlns:android="http://schemas.android.com/apk/res/android"
class="com.example.myapp.DashedRingDrawable"/>
對于 API 24 之前的 API,您需要以編程方式使用此自定義可繪制物件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/488245.html
