OpenHarmony滑杆样式自定义指南
一、实现思路与方案对比
二、基于系统 Slider 的实用自定义
@Entry
@Component
struct MySliderPage {
@State value: number = 30
@State min: number = 0
@State max: number = 100
build() {
Column({ space: 12 }) {
// 标题
Text('自定义滑杆示例').fontSize(18).fontWeight(FontWeight.Bold)
// 滑杆
Slider({
value: this.value,
min: this.min,
max: this.max,
step: 1,
style: SliderStyle.OutSet // 可选:OutSet / InSet
})
.width('100%')
.trackColor(Color.Gray)
.selectedColor(Color.Blue)
.thumbColor(Color.White)
.thumbSize({ width: 24, height: 24 })
.trackThickness(6)
.showTips(true)
.onChange((v: number) => {
this.value = v
})
// 刻度与标签
Row() {
Text(`${this.min}`).fontSize(12)
Blank()
Text(`${this.max}`).fontSize(12)
}
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
Text(`当前值:${this.value}`).fontSize(16)
}
.padding(16)
}
}
上述做法覆盖了布局适配、样式定制、交互反馈与复用封装等常见需求,适合大多数业务场景。
三、完全自定义滑杆的实现思路
@Entry
@Component
struct CustomSlider {
@State value: number = 30
@State min: number = 0
@State max: number = 100
private sliderWidth: number = 0
private dragging: boolean = false
build() {
Column({ space: 12 }) {
Stack({ alignContent: Alignment.Start }) {
// 轨道
Rect()
.width('100%')
.height(8)
.fill(Color.Gray)
.borderRadius(4)
// 已选进度
Rect()
.width(px2vp(this.sliderWidth * (this.value - this.min) / (this.max - this.min)))
.height(8)
.fill(Color.Blue)
.borderRadius(4)
// 滑块
Circle({ width: 24, height: 24 })
.fill(Color.White)
.shadow({ radius: 4, color: Color.Black, offsetX: 0, offsetY: 2 })
.scale(this.dragging ? 1.2 : 1)
.gesture(
PanGesture({ direction: GestureDirection.Horizontal })
.onUpdate((e) => {
const dx = e.fingerList[0].globalX - this.startX
const percent = Math.max(0, Math.min(1, dx / this.sliderWidth))
this.value = this.min + percent * (this.max - this.min)
})
.onEnd(() => { this.dragging = false })
)
.onAreaChange((oldV, newV) => {
this.sliderWidth = newV.width
this.startX = newV.globalX
})
}
.width('100%')
.height(32)
.padding({ left: 12, right: 12 })
Text(`当前值:${this.value.toFixed(0)}`).fontSize(16)
}
.padding(16)
}
}
该方案通过组合与手势实现任意外观,适合品牌化设计与复杂交互需求。
四、样式复用与主题切换
// 复用轨道样式
@Styles function trackStyle() {
.height(8).borderRadius(4).fill(Color.Gray)
}
@Styles function thumbStyle() {
.width(24).height(24).fill(Color.White)
.shadow({ radius: 4, color: Color.Black, offsetX: 0, offsetY: 2 })
}
// 扩展 Slider 的便捷方法
@Extend(Slider) function withThumbSize(w: number, h: number) {
.thumbSize({ width: w, height: h })
}
// 主题切换(示意)
class SliderModifier implements AttributeModifier<SliderAttribute> {
isDark: boolean = false
applyNormalAttribute(instance: SliderAttribute): void {
if (this.isDark) {
instance.selectedColor(Color.Orange)
instance.trackColor(Color.DarkGray)
} else {
instance.selectedColor(Color.Blue)
instance.trackColor(Color.Gray)
}
}
}
通过 @Styles/@Extend/AttributeModifier 的组合,可以在不同文件与页面间统一滑杆风格,并快速切换主题。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。