UI 教程:自绘元素
本篇是 UI 教程的第 16–18 章。前面各章用的 Button、Checkbox、ScrollArea、Popover 都来自 scoop.ui.component,而它们本身也只是普通 Scoop 代码,建立在 scoop.ui 公开的同一套接口之上。本篇介绍这套接口:第 16 章从零写一个自绘控件,第 17 章让它获得焦点、主题外观、文字排版和着色器效果,第 18 章编写自己的弹层、滚动容器和按需构建的长列表。
在动手之前先判断是否真的需要自绘:能用 frame、row、column、stack 和 styled 组合出来的界面,就不必写 Element。需要自定义的几何形状、特殊的指针交互、自己的布局算法,或者想按需构建成千上万个子项时,才轮到本篇的内容。
16. 自绘 Element
16.1 Component 与 Element
到目前为止写的都是 Component:它保存状态,在 render() 中返回一棵 View 描述,具体的测量和绘制交给描述中的其他节点。Element 则是真正“干活”的节点:它自己决定尺寸、子项放在哪里、哪块区域接收输入、画什么。
在 render 中用 element(props, create, children) 描述一个 Element:
return element(
MeterInput(level.value, 10, { next -> level.value = next }),
{ props, mount -> Meter(props, mount) },
[caption]
)
props是传给元素的输入,每次 render 都会生成新值;元素通过Props<P>.value读取最新输入。这里把当前级别和一个“请求修改”的回调一起传下去:元素本身不保存业务状态,只负责显示和把用户操作报告给上层。create只在首次挂载时调用,创建元素实例;之后的 render 只更新 Props,实例和它的字段都保留。children是元素的子 View,元素在布局时按下标测量和放置它们。不需要 Props 时可以写element({ mount -> MyElement(mount) }, children)。
Element 类继承 Element<L>,L 是 measure 交给 scene 的布局数据类型,没有额外数据时用 Unit。
16.2 一个完整的自绘控件
下面的程序画了一个可以点击或拖动的级别条:蓝色填充用弹簧动画跟随当前级别,上方三角形标出位置,下方是一个普通的 Label 子项。它只使用 scoop.ui 及下层的图形、Surface 接口;Label 来自控件库,只是作为子项演示。
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.graphics.text:0.1.0
//! dep: scoop:scoop.surface:0.1.0
//! dep: scoop:scoop.window:0.1.0
import scoop.graphics.*
import scoop.graphics.text.TextAlignment
import scoop.surface.*
import scoop.ui.*
import scoop.ui.component.label
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.macos.macosTheme
import scoop.window.*
/** Props of the self-drawn meter: the current level and how to change it. */
struct MeterInput(val level: Int, val steps: Int, val onChange: (Int) -> Unit)
class MeterDemo(scope: ComponentScope): Component(scope) {
private val level = state(3)
public override fun render(): View {
val level = this.level
val caption =
label(f"Level ${level.value} of 10") { settings { alignment = TextAlignment.Center } }
return element(
MeterInput(level.value, 10, { next -> level.value = next }),
{ props, mount -> Meter(props, mount) },
[caption]
)
}
}
class Meter(private val props: Props<MeterInput>, scope: ComponentScope): Element<Unit>(scope) {
private var area: InputArea? = None
private var fill: Animatable<Double>? = None
private var marker: Path? = None
private var dragging = false
private var track = Rect(0.0, 0.0, 0.0, 0.0)
public override fun onMount() {
// Resources registered here are closed automatically on unmount.
marker =
Some(
scope.resource {
path {
moveTo(Point(-7.0, 0.0))
lineTo(Point(7.0, 0.0))
lineTo(Point(0.0, 9.0))
closeContour()
}
}
)
fill = Some(scope.animation(fraction()))
area = Some(scope.createArea { current, event -> handle(current, event) })
}
/** Pointer handling: press or drag picks a level, release ends the drag. */
private fun handle(current: RoutedEventContext, event: InputEvent) {
if (current.phase != RoutedPhase.Target)
return
when (event) {
case Pointer(InputPointerEvent.Button(_, MouseButton.Left, val button, _)) -> {
dragging = button == ElementState.Pressed
if (dragging)
pick(current.localPosition!!)
current.consume()
}
case Pointer(InputPointerEvent.Moved(_)) -> {
if (dragging) {
pick(current.localPosition!!)
current.consume()
}
}
case Pointer(InputPointerEvent.Cancelled(_, _)) -> dragging = false
else -> {}
}
}
private fun fraction(): Double = props.value.level.toDouble() / props.value.steps.toDouble()
/** Converts a local pointer position into a level and reports it upward. */
private fun pick(position: Point) {
var ratio = (position.x - track.x) / track.width
if (ratio < 0.0)
ratio = 0.0
if (ratio > 1.0)
ratio = 1.0
val next = (ratio * props.value.steps.toDouble() + 0.5).toInt()
if (next != props.value.level)
props.value.onChange(next)
}
/** The track sits in a 96-point band centered vertically in the element. */
private fun trackRect(size: Size): Rect =
Rect(24.0, (size.height - 96.0) / 2.0 + 24.0, size.width - 48.0, 14.0)
public override fun update(): UiInvalidation {
// New Props arrived: start a spring toward the new level.
val target = fraction()
if (fill!!.target != target)
fill!!.animateTo(target, AnimationSpec.Spring())
return UiInvalidation.Scene
}
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
Unit
> {
val size = constraints.constrain(Size(constraints.maxWidth ?: 360.0, 96.0))
val bar = trackRect(size)
// Measure the caption as wide as the track, then place it below the track.
context.measureChild(0L, Constraints(maxWidth = Some(bar.width)))
context.placeChild(0L, Point(bar.x, bar.y + 28.0))
return LayoutResult(LayoutMetrics(size), Unit)
}
public override fun scene(context: SceneContext, layout: Unit) {
track = trackRect(context.size)
val filled = Rect(track.x, track.y, track.width * fill!!.value, track.height)
context.place(area!!, Rect(0.0, 0.0, context.size.width, context.size.height))
// Background drawing first, then the child caption, then the marker on top.
context.draw {
paint ->
paint.canvas.clear(Color(0.96, 0.97, 0.99))
paint.canvas.drawRoundRect(track, 7.0, 7.0, Paint(Color(0.86, 0.88, 0.92)))
paint.canvas.drawRoundRect(filled, 7.0, 7.0, Paint(Color(0.18, 0.42, 0.85)))
}
context.children()
context.draw {
paint ->
paint.canvas.save()
paint.canvas.translate(filled.x + filled.width, track.y - 11.0)
paint.canvas.drawPath(marker!!, Paint(Color(0.12, 0.27, 0.65)))
paint.canvas.restore()
}
}
}
fun main() {
val source = ThemeSource(macosTheme(ThemeMode.Light))
context(source) {
runUiApplication("Meter", { scope -> MeterDemo(scope) })
}
}
scoop run ui-custom-meter.scoop --release

Windows 写作 sco run ui-custom-meter.scoop --release。在条上点击或按住拖动,下面的文字立即变成新的级别,填充部分则以弹簧动画滑到新位置。
接下来按生命周期的顺序拆解这个程序。
16.3 生命周期:onMount、update、onUnmount
| 阶段 | 调用时机 | 适合做什么 |
|---|---|---|
| 构造 | 首次挂载,create 被调用 |
初始化不需要窗口的普通字段 |
onMount() |
节点挂入窗口后、首次测量前 | 创建 Path、图片等资源,输入区域,动画,焦点目标 |
update() |
每次挂载完成后,以及每次收到新 Props 后 | 把新输入同步到资源和动画上,返回需要重做的工作 |
onUnmount() |
节点卸载前 | 释放没有交给 scope 管理的东西(多数情况下不需要) |
update() 返回 UiInvalidation:Layout 表示尺寸或子项位置可能改变,需要重新 measure;Scene 表示只需要重新绘制;None 表示什么都不用做。Meter 的新级别只影响填充宽度,所以返回 Scene。
onMount() 中创建的东西都交给 ComponentScope 管理:
scope.resource { ... }登记任何Closeable资源,例如path { ... }构造的 Path,或图片、缓存;scope.createArea(...)创建输入区域;scope.animation(initial)创建绑定到窗口时间轴的Animatable。
卸载时,作用域会先停用输入和动画、调用 onUnmount(),再按登记的相反顺序关闭资源。所以示例中不需要为每个资源写 use 或在 onUnmount() 中手动关闭。不要在 measure、scene 或 draw 中创建资源——它们每帧都可能执行,会造成泄漏。
16.4 measure:约束、尺寸与子项
measure(context, constraints) 回答两个问题:我有多大,子项放在哪里。
Constraints 给出允许的宽高范围:minWidth、maxWidth: Double?、minHeight、maxHeight: Double?,最大值为 None 表示不限制。constraints.constrain(size) 把期望尺寸夹到范围内,Constraints.tight(size) 构造一个固定尺寸的约束。根元素收到的是窗口尺寸的固定约束,所以 Meter 总是和窗口一样大,它把 96 点高的内容区放在垂直居中的位置。
子项通过 MeasureContext 处理:
context.measureChild(index, constraints)测量第index个子项,返回它的LayoutMetrics(尺寸和可选的基线);context.placeChild(index, origin)把子项放在本元素局部坐标中的origin。
一个子项在放置前可以用不同约束重复测量(例如先试探自然宽度再决定),每个子项本帧最多放置一次。没有放置的子项保持挂载和状态,只是这一帧不绘制、不接收输入。Meter 给 Label 一个与轨道同宽的约束,并让 Label 自己用 settings { alignment = TextAlignment.Center } 居中文字。
measure 返回 LayoutResult(metrics, data)。metrics 是 LayoutMetrics(size, alphabeticBaseline, ...);data 是类型为 L 的布局数据,会原样交给 scene。如果布局数据持有需要关闭的资源,可以传第三个参数 dispose,在这份布局被替换时调用。
16.5 scene:输入区域、子项与绘制顺序
scene(context, layout) 用 SceneContext 描述这一帧的画面,它会按调用顺序执行:
context.place(area, rect):把输入区域放到局部坐标的矩形(或 Path)上。区域的命中范围以这里为准,而不是看画了什么;context.draw { paint -> ... }:提交一段绘制;context.children():在此处绘制所有已放置的子项。
在 children() 前后各写一个 draw 块,就得到“背景—子项—前景”三层:Meter 先画轨道和填充,再画 Label,最后画三角形,所以三角形总在最上面。
SceneContext 还提供作用于后续内容(包括子项和输入区域)的变换和裁剪:translate、scale、rotate、concat(transform)、clipRect、clipPath,以及配对使用的 save()/restore()、saveLayer(opacity, filter)。用 withState { local -> ... } 可以把这些修改限制在一个块里。下面的元素只显示子项左侧移去 10 点后、宽 120 点的部分:
/** Shows only the part of its child that fits a 120x40 window, shifted left by 10. */
class Peek(scope: ComponentScope): Element<Unit>(scope) {
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
Unit
> {
context.measureChild(0L, Constraints())
context.placeChild(0L, Point(0.0, 0.0))
return LayoutResult(LayoutMetrics(constraints.constrain(Size(120.0, 40.0))), Unit)
}
public override fun scene(context: SceneContext, layout: Unit) {
context.withState {
local ->
local.clipRect(Rect(0.0, 0.0, 120.0, 40.0))
local.translate(-10.0, 0.0)
local.children()
}
}
}
注意区分两种变换:在 SceneContext 上做的变换会同时影响绘制和之后登记的命中区域;在 draw 块内部对 Canvas 做的 save/translate/restore 只影响这一段绘制。Meter 画三角形时用的是后者,它不需要改变点击范围。
16.6 draw:PaintContext 与 Canvas
draw 块收到 PaintContext,其中 paint.canvas 是本帧的 Canvas,paint.size 是元素尺寸,paint.time 是本帧时间。示例用到的 Canvas 方法有 clear(color)、drawRoundRect(rect, rx, ry, paint)、drawCircle(center, radius, paint)、drawPath(path, paint) 和 save/translate/restore;Paint(color) 默认填充,Paint(color, PaintingStyle.Stroke, width) 描边。
Canvas 只在当次回调中有效,不能保存到字段里留到以后使用。draw、scene 和 measure 中也不能写 State,否则会报错;要改变状态,应该在输入回调或生命周期方法中进行。
16.7 输入与动画
scope.createArea(focusable, textInput, parent, handler) 创建一个 InputArea,handler(context, event) 接收路由到这个区域的事件。事件按阶段传递,context.phase 是 RoutedPhase 之一:Capture(从外向内)、Target(到达目标区域)、Bubble(从内向外)、Default(路由结束后的默认动作)和 Notification(状态通知)。Meter 只处理自己作为目标时的指针事件:
private fun handle(current: RoutedEventContext, event: InputEvent) {
if (current.phase != RoutedPhase.Target)
return
when (event) {
case Pointer(InputPointerEvent.Button(_, MouseButton.Left, val button, _)) -> {
dragging = button == ElementState.Pressed
if (dragging)
pick(current.localPosition!!)
current.consume()
}
// ...
}
}
current.localPosition 是指针在区域局部坐标中的位置,current.consume() 表示事件已处理。处理器里调用的 props.value.onChange(next) 修改了上层组件的 State,上层重新 render,新 Props 到达后 update() 被调用。
动画用 scope.animation(initial) 创建,返回 Animatable<T>(支持 Double、Point、Size、Color)。animateTo(target, AnimationSpec.Spring()) 从当前值开始向目标运动,target 是目标值,value 是本帧的采样值。在 scene 中读取 fill!!.value,框架在动画进行期间自动安排后续帧,并直接重新执行 scene,不会重跑上层的 render。
16.8 停帧:静止时什么都不做
Scoop UI 只在有事要做时才绘制:State 改变、Props 更新、显式的帧请求或活动动画。没有这些时,框架不遍历组件树,窗口不请求新帧,CPU 占用为零。Meter 的动画结束后就停在最后一帧,直到下一次点击。
自绘时要配合这个原则:
- 不要在 draw 中启动动画或请求帧,也不要用定时器“每帧刷新”;
- 只有视觉变化而没有状态变化时(例如悬停高亮),在输入回调中调用
scope.requestFrame()请求一帧,或者使用下一章的交互助手; - 尺寸变化需要重新布局时调用
scope.requestLayout(),或在update()中返回Layout。
17. 让自绘控件接入框架能力
本章编写一个“任务行”控件:左边是主题风格的复选框标记,右边是标题;整行可以点击、悬停时显示背景、能用 Tab 聚焦并用空格键切换。
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.surface:0.1.0
//! dep: scoop:scoop.window:0.1.0
import scoop.graphics.*
import scoop.surface.InputArea
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.style.*
import scoop.ui.style.macos.macosTheme
import scoop.window.accessibility.*
class TaskList(scope: ComponentScope): Component(scope) {
private val theme = currentThemeSource()
private val first = state(false)
private val second = state(true)
public override fun render(): View {
val first = this.first
val second = this.second
val current = this.theme.read(scope)
var finished = 0
if (first.value)
finished += 1
if (second.value)
finished += 1
val done = finished
val content =
column {
spacing = 6.0
add(taskRow(current, "Write the outline", first))
add(taskRow(current, "Review the examples", second))
row {
spacing = 12.0
alignment = CrossAlignment.Center
label(f"${done} of 2 done")
button(
"Reset",
{
first.value = false
second.value = false
}
)
}
}
return frame(content) {
padding = Some(Insets.all(20.0))
alignment = Alignment(AxisAlignment.Start, AxisAlignment.Start)
style { background(Some(Paint(current.tokens.palette.background.background))) }
}
}
}
/** The theme travels in Props, so a theme switch updates every row. */
class TaskInput(val theme: Theme, val done: Boolean, val toggle: () -> Unit)
fun taskRow(theme: Theme, title: String, done: State<Boolean>): View =
element(
TaskInput(theme, done.value, { done.value = !done.value }),
{ props, mount -> TaskToggle(props, mount) },
[label(title)]
)
/** Layout result: where the checkbox marker goes inside the row. */
struct TaskLayout(val marker: Rect)
class TaskToggle(private val props: Props<TaskInput>, scope: ComponentScope): Element<TaskLayout>(
scope
) {
private val checkbox = scope.semantics(SemanticRole.Checkbox)
private var area: InputArea? = None
private var press: Press? = None
private var painters: ThemePainterCache? = None
private var decoration: StylePainter? = None
public override fun onMount() {
painters = Some(scope.resource { ThemePainterCache() })
decoration = Some(scope.resource { StylePainter() })
val region = scope.createArea(focusable = true)
area = Some(region)
checkbox.bindFocus(Some(scope.focusTarget(region)))
// Use the visible task label as the accessible name.
checkbox.mergeLabels = true
scope.routeSemanticsChildren(Some(checkbox))
press = Some(scope.press(region) { props.value.toggle() })
}
public override fun update(): UiInvalidation {
val checked =
if (props.value.done)
SemanticChecked.On
else
SemanticChecked.Off
checkbox.update(
SemanticProperties(checked = Some(checked)),
SemanticActions(
toggle =
Some {
props.value.toggle()
SemanticActionResult.Completed
}
)
)
painters!!.get(props.value.theme)
return UiInvalidation.Layout
}
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
TaskLayout
> {
val theme = props.value.theme
val side = theme.checkboxMetrics(direction = context.layoutDirection).suggestedSize.width
val padding = 8.0
val gap = 8.0
val text = context.measureChild(0L, Constraints(maxWidth = Some(280.0)))
val height =
if (text.size.height > side)
text.size.height
else
side
context.placeChild(
0L,
Point(padding + side + gap, padding + (height - text.size.height) / 2.0)
)
val size =
constraints.constrain(
Size(padding * 2.0 + side + gap + text.size.width, height + padding * 2.0)
)
return LayoutResult(
LayoutMetrics(size),
TaskLayout(Rect(padding, padding + (height - side) / 2.0, side, side))
)
}
public override fun scene(context: SceneContext, layout: TaskLayout) {
val input = props.value
val region = area!!
// Reading the Press state here schedules a new frame when it changes.
val state = press!!.interaction
val visual =
CheckboxVisual(
if (input.done)
CheckMark.On
else
CheckMark.Off,
InteractionVisual(
hovered = state.hovered,
pressed = state.pressed,
focusVisible = state.focusVisible
)
)
val geometry =
input.theme.checkboxGeometry(layout.marker, visual, direction = context.layoutDirection)
val palette = input.theme.tokens.palette
// A public Style draws the row background; the hover state just picks another color.
val rowStyle =
style {
background =
if (state.hovered)
Some(Paint(palette.accent.background))
else
None
corners = Corners.all(input.theme.tokens.corners.medium)
}
val bounds = Rect(0.0, 0.0, context.size.width, context.size.height)
context.place(region, bounds)
context.semantics(checkbox, bounds)
decoration!!.scene(context, rowStyle) {
content ->
content.draw {
paint -> painters!!.get(input.theme).drawCheckbox(paint.canvas, geometry, visual)
}
content.children()
}
}
}
fun main() {
val source = ThemeSource(macosTheme(ThemeMode.Light))
context(source) {
runUiApplication("Tasks", { scope -> TaskList(scope) })
}
}
scoop run ui-custom-task.scoop --release

用鼠标点击或用手指轻点一行,下面的完成计数随之变化。按 Tab 聚焦任务行后可以用空格或回车切换。用读屏器导航时,每一行都是有标题和勾选状态的复选框,执行切换动作也会更新同一个计数。
17.1 可聚焦:focusTarget
要让元素参与键盘焦点,需要两步:
- 创建可聚焦的输入区域:
scope.createArea(focusable = true); - 用
scope.focusTarget(area, options)把它登记为焦点目标。
登记后它就和内置控件一样出现在 Tab 顺序中。FocusOptions(handle, tabStop, order) 中,handle 是可选的 FocusHandle,用于在程序中调用 requestFocus() 或查询 hasFocus;tabStop = false 使它只能被点击或程序聚焦;order 默认为 0,相同值按挂载顺序排列。区域本身提供 isFocusActive、isFocusVisible 等查询:通常只在键盘导航时(isFocusVisible)才显示焦点环。
17.2 交互助手
指针按下、拖出取消、空格键在松开时才触发……这些细节每个按钮类控件都要处理。scoop.ui 把它们做成了可以直接使用的助手,都通过 ComponentScope 创建并随挂载自动关闭:
| 助手 | 用途 |
|---|---|
scope.press(area, options) { ... } |
点击、轻点、空格或回车激活,interaction 给出 hovered/pressed/focused/focusVisible |
scope.drag(area, options, accepts) { event -> ... } |
鼠标或直接接触拖动,DragOptions 可分别启用两种来源 |
scope.longPress(area) { sample -> ... } |
静止长按触发,滚动接管或触点取消后结束 |
scope.swipeGesture(area) { sample -> ... } |
识别指定轴的轻扫,按方向执行一次命令 |
scope.transformGesture(area) { event -> ... } |
接收捏合倍率和旋转角度,用增量调整自绘内容 |
scope.presence(open, options) |
打开/关闭的呈现阶段和 0–1 的进入/退出进度 |
scope.hover(trigger, open, options) |
悬停一段时间后打开、离开后关闭,处理触发区和弹层之间的移动 |
scope.activeItems(source, active, options, reveal) |
列表中的“当前项”随方向键移动,焦点留在原处(例如组合框) |
scope.typeahead(source, currentKey, onMatch, options) |
非编辑列表中按字母快速跳转 |
scope.keyNavigation(options) |
一组焦点目标之间的方向键与 Home/End 导航 |
TaskToggle 用的是 scope.press:
val region = scope.createArea(focusable = true)
area = Some(region)
checkbox.bindFocus(Some(scope.focusTarget(region)))
checkbox.mergeLabels = true
scope.routeSemanticsChildren(Some(checkbox))
press = Some(scope.press(region) { props.value.toggle() })
press.interaction 是一个 State;在 scene 中读取它,状态变化时框架会自动重新绘制这个元素,无需手动 requestFrame()。
checkbox 是在挂载时创建的 SemanticRole.Checkbox 节点。这里复用真实焦点和可见标签。元素在 update() 发布勾选状态与切换动作,在 scene() 用 context.semantics(checkbox, bounds) 登记整行范围。见触摸、手势与无障碍。
17.3 用 ThemePainterCache 画主题部件
自绘控件不需要自己模仿各套主题的复选框。主题提供“几何查询”,ThemePainter 按同一份几何绘制:
theme.checkboxMetrics(options, direction):建议尺寸、最小尺寸、焦点外扩等,用于 measure;theme.checkboxGeometry(bounds, visual, options, direction):给定最终位置,算出外框、标记线段、焦点环;painter.drawCheckbox(canvas, geometry, visual):在 Canvas 上绘制。
visual 是 CheckboxVisual(mark, interaction):mark 为 CheckMark.Off、On 或 Mixed,interaction 是 InteractionVisual(enabled, hovered, pressed, focusVisible, ...)。表面(surfaceGeometry/drawSurface)、单选框(radioGeometry/drawRadio)和滚动条(scrollbarGeometry/drawScrollbar)用法相同。
Painter 持有的原生资源由 ThemePainterCache 管理。在 onMount 中用 scope.resource { ThemePainterCache() } 创建缓存,绘制时调用 painters.get(theme)。TaskList 在 render 中读取 this.theme.read(scope),通过 TaskInput 将应用了窗口偏好的主题传给每一行。在 update() 中先调用 painters!!.get(props.value.theme),绘制前就能替换 painter 并关闭旧资源。
17.4 用 StylePainter 套用公共 Style
第 15 章的 Style(背景、边框、圆角、阴影、内容效果)也可以在自绘元素里使用。在 onMount 中 scope.resource { StylePainter() },在 scene 中:
decoration!!.scene(context, rowStyle) {
content ->
content.draw {
paint -> painters!!.get(input.theme).drawCheckbox(paint.canvas, geometry, visual)
}
content.children()
}
StylePainter.scene(context, style) { content -> ... } 先画阴影和背景,再执行回调中的内容(并应用 contentEffects),最后画边框,顺序与 styled 完全相同。回调收到的仍是 SceneContext,可以继续 draw 和 children()。TaskToggle 根据悬停状态选择有无背景色,圆角取自主题的 tokens.corners.medium。另有 scene(context, bounds, style) { ... } 指定矩形,以及 paint(canvas, bounds, style) 供离屏绘制使用。
17.5 文本:ParagraphHost 与行内子项
在自绘元素中排版文字,使用 scoop.ui.text 的 ParagraphHost。它负责段落布局、文字绘制和缓存,还能把普通 UI 子项(按钮、图片、徽标)嵌入文字中,像一个“字”一样参与换行和基线对齐:
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.graphics.text:0.1.0
import scoop.graphics.*
import scoop.graphics.text.*
import scoop.ui.*
import scoop.ui.component.button
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.macos.macosTheme
import scoop.ui.text.*
val counterKey = InlineKey.Text("counter")
class NoteDemo(scope: ComponentScope): Component(scope) {
private val count = state(0)
public override fun render(): View {
val count = this.count
// A real Button sits inside the text, aligned to the baseline like a word.
val note =
inlineText {
style {
fontSize = 18.0
color = Color(0.12, 0.12, 0.14)
}
text("Self-drawn paragraphs can host live controls: ")
// Buttons fill the width they are offered, so give this one a fixed size.
inline(counterKey, button(f"${count.value}", { count.value += 1 }), "[counter]") {
size = Some(Size(48.0, 26.0))
}
text(" — the button keeps its state while the text around it reflows.")
}
return element(
note,
{ props, mount -> Note(props, mount) },
inlineChildren(note.content, note.inlines)
)
}
}
class Note(private val props: Props<InlineText>, scope: ComponentScope): Element<
ParagraphMeasurement
>(scope) {
private var host: ParagraphHost? = None
public override fun onMount() {
host = Some(scope.resource { ParagraphHost() })
}
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
ParagraphMeasurement
> {
val margin = 24.0
val width = (constraints.maxWidth ?: 480.0) - margin * 2.0
// The host measures and places the inline children, then lays out the text.
val measured =
host!!.measure(
context,
Constraints(maxWidth = Some(width)),
scope.defaultFonts,
props.value.content,
None,
props.value.inlines
)
val text = measured.metrics.size
return LayoutResult(
LayoutMetrics(
constraints.constrain(Size(text.width + margin * 2.0, text.height + margin * 2.0))
),
measured,
{ measured.close() }
)
}
public override fun scene(context: SceneContext, measured: ParagraphMeasurement) {
context.draw { paint -> paint.canvas.clear(Color(0.97, 0.97, 0.98)) }
context.translate(24.0, 24.0)
host!!.scene(context, measured)
}
}
fun main() {
val source = ThemeSource(macosTheme(ThemeMode.Light))
context(source) {
runUiApplication("Inline views", { scope -> NoteDemo(scope) })
}
}
scoop run ui-custom-paragraph.scoop --release

窗口中是一段文字,中间嵌着一个显示计数的蓝色按钮;点击按钮计数增加。把窗口拉窄,文字重新换行,按钮随文字移动,计数保持不变。
几个要点:
inlineText { ... }用text(...)和inline(key, view, alternateText)构造内容;InlineKey把文字中的占位和子 View 对应起来,alternateText用于复制等场合。它产生content(StyledText)和inlines(InlineView数组)。- 描述元素时,用
inlineChildren(content, inlines)生成 children,顺序与文字中的占位一致。 - Element 在 onMount 中
scope.resource { ParagraphHost() };measure 中调用host.measure(context, constraints, fonts, content, settings, inlines),它会测量并放置行内子项,返回ParagraphMeasurement;scene 中调用host.scene(context, measured)绘制文字和子项。ParagraphMeasurement需要关闭,所以作为布局数据返回时传入{ measured.close() }。 scope.defaultFonts是窗口的默认字体集合。- 行内子项默认按自然尺寸测量。Button 会占满给它的宽度,所以示例用
size = Some(Size(48.0, 26.0))给了固定尺寸。
文字或子项变化时,ParagraphHost 会尽量复用已有布局;行内子项的 key 稳定,换行和重排都不会让按钮丢失状态。
17.6 绘制缓存:drawLayer
普通的 draw 块每次绘制都会执行。如果一块内容绘制成本较高、且有可靠的“版本号”,可以用 drawLayer 缓存它:
/** A badge whose pixels depend only on its count. */
class Badge(private val props: Props<Int>, scope: ComponentScope): Element<Unit>(scope) {
private val paintKey = PaintKey()
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
Unit
> = LayoutResult(LayoutMetrics(constraints.constrain(Size(40.0, 40.0))), Unit)
public override fun scene(context: SceneContext, layout: Unit) {
val count = props.value
// The revision must change whenever anything drawn inside the block changes.
context.drawLayer(paintKey, Rect(0.0, 0.0, 40.0, 40.0), count.toLong()) {
paint ->
val color =
if (count > 9)
Color(0.86, 0.18, 0.16)
else
Color(0.18, 0.42, 0.85)
paint.canvas.drawCircle(Point(20.0, 20.0), 18.0, Paint(color))
}
}
}
PaintKey由元素持有,每个 key 在一次 scene 中只能使用一次;bounds是缓存的范围,回调在独立的局部坐标中绘制;revision必须覆盖所有影响像素的输入:状态、时间、动画、主题和资源。这里像素只取决于count,所以直接用它。忘记把某个输入算进版本号,画面就会停留在旧内容上。
缓存只节省绘制;场景、输入区域和子项每帧照常装配。拿不准时就用普通 draw,ParagraphHost 等内置部件已经在内部使用了这套机制。
17.7 SkSL 着色器与背景效果
纯色和渐变用普通的 Paint 就能画。需要逐像素计算的图案,或者“毛玻璃”这类读取背后内容的效果时,可以用 SkSL(Skia 的着色语言)编写程序,交给 scoop.graphics 执行:
- 编译程序。
ShaderProgram.compile(source)编译 SkSL,源码有错误时抛出带编译器诊断的GraphicsException。一个程序可以被多个元素共用,在组件或元素中用scope.resource { ... }创建,由 scope 负责关闭。 - 填充形状。
program.makeShader { setColor(...); setFloat(...) }为 uniform 绑定一组值,得到一份不再改变的Shader;canvas.drawRect(rect, paint, Some(shader))用它填充矩形。颜色 uniform 写作layout(color) uniform half4,用setColor绑定;float、float2等用setFloat、setFloats,没有绑定的数值 uniform 为 0。 - 图像滤镜。
ImageFilter.blur(sigmaX, sigmaY)是高斯模糊;ImageFilter.runtimeShader(program, "background", sampleRadius) { ... }用 SkSL 处理输入图像,background是程序中uniform shader的名字,sampleRadius声明取样最多偏离当前像素多远。 - 背景效果。
StylePainter.scene(context, bounds, style, Some(filter)) { ... }先用滤镜处理当前图层中已经画出的内容,再在上面画 Style 的底色、边框和子项。底层对应 Canvas 的drawBackdrop(outline, filter)。
下面的程序用 SkSL 画出蓝色的等高线,在中间放一块磨砂玻璃面板。保存为 ui-custom-shader.scoop(下载):
//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.shadcn:0.1.0
import scoop.graphics.*
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.style.*
import scoop.ui.style.shadcn.shadcnTheme
/** SkSL: contour lines whose color comes from a uniform. */
val wavesSource = """
layout(color) uniform half4 ink;
uniform float phase;
half4 main(float2 p) {
float level = (p.y + 26.0 * sin(p.x * 0.018 + phase)) / 16.0;
float line = 1.0 - smoothstep(0.03, 0.12, abs(fract(level) - 0.5));
float band = 0.5 + 0.5 * sin(level * 0.6 + phase);
return half4(mix(half3(0.97), ink.rgb, 0.18 + 0.32 * band + 0.5 * line), 1.0);
}
"""
class GlassModel {
val frosted = state(true)
}
/** Fills itself with the shader and draws a glass panel around its only child. */
class Poster(private val frosted: Props<Boolean>, program: ShaderProgram, scope: ComponentScope) :
Element<Rect>(scope) {
private val waves = scope
.resource {
program
.makeShader {
setColor("ink", Color(0.15, 0.35, 0.85))
setFloat("phase", 0.8f)
}
}
private val blur = scope.resource { ImageFilter.blur(9.0, 9.0) }
private val painter = scope.resource { StylePainter() }
private val glass = style {
corners = Corners.all(20.0)
background = Some(Paint(Color(1.0, 1.0, 1.0, 0.3)))
border = Some(Border.all(1.0, Color.White.withAlpha(0.85)))
clipContent = true
}
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
Rect
> {
val size = constraints
.constrain(Size(constraints.maxWidth ?: 640.0, constraints.maxHeight ?: 420.0))
val panel = Rect((size.width - 320.0) * 0.5, (size.height - 132.0) * 0.5, 320.0, 132.0)
// Measure the child at its natural size, then center it inside the panel.
val child = context.measureChild(0L, Constraints())
context
.placeChild(
0L,
Point(
panel.x + (panel.width - child.size.width) * 0.5,
panel.y + (panel.height - child.size.height) * 0.5
)
)
return LayoutResult(LayoutMetrics(size), panel)
}
public override fun scene(context: SceneContext, layout: Rect) {
val size = context.size
context
.draw { paint ->
paint
.canvas
.drawRect(
Rect(0.0, 0.0, size.width, size.height),
Paint(Color.White),
Some(waves)
)
}
// The backdrop filter samples what this layer has drawn so far: the waves.
val backdrop = if (frosted.value) Some(blur) else None
painter.scene(context, layout, glass, backdrop) { local -> local.children() }
}
}
class GlassDemo(private val model: GlassModel, scope: ComponentScope) : Component(scope) {
private val program = scope.resource { ShaderProgram.compile(wavesSource) }
public override fun render(): View {
val model = this.model
val program = this.program
val active = model.frosted.value
val content = column {
typography("Frosted glass", TypographyRole.H4)
button(if (active) "Blur on" else "Blur off", { model.frosted.value = !active }) {
variant = ButtonVariant.Secondary
}
spacing = 12.0
alignment = CrossAlignment.Center
}
return element(active, { props, mount -> Poster(props, program, mount) }, [content])
}
}
fun main() {
val model = GlassModel()
context(ThemeSource(shadcnTheme(ThemeMode.Light))) {
runUiApplication("Shader", { scope -> GlassDemo(model, scope) })
}
}
scoop run ui-custom-shader.scoop --release

窗口中铺满由着色器逐像素计算的波浪线;中间面板背后的线条被高斯模糊,上面叠加半透明的白色底色和细边框。点 Blur on 关闭模糊,面板变成普通的半透明底,线条清晰地透过来;再点一次恢复。
几点说明:
- 坐标是元素的局部逻辑坐标。 着色器
main(float2 p)中的p以元素左上角为原点,单位与布局相同,不随屏幕缩放改变。 - 背景只采样同一图层中先画的内容。
Poster先画波浪线再画面板,所以面板模糊的是波浪线。面板的glassStyle 设置了clipContent = true,子项不会画出圆角之外。 - 静止时不产生帧。 Shader 和滤镜都是参数的快照,持有它们不会启动帧循环;要改变参数,创建新的快照并关闭旧的。示例在
scope.resource中创建它们,元素卸载时一并关闭。
工具链附带的 scoop.ui.component/examples/glass 在可滚动的色样列表上放置固定工具栏,分别对比高斯模糊和用 runtimeShader 写的折射效果。把该目录复制到自己的工作目录后运行 scoop run --release。
18. 自定义弹层与容器
18.1 portal 与锚点
portal(open, content) { ... } 把一个 View 送到窗口的弹层出口中显示。它在原位置只占约束允许的最小尺寸,内容越过祖先的裁剪和变换,画在页面之上;但在逻辑上仍属于原来的组件树,输入路由、Tab 顺序和状态都跟着原位置走。open 是 Binding<Boolean>,与第 11 章的控件弹层一样,它是“是否打开”的唯一来源。
要让弹层贴着某个元素出现,需要一个 LayoutAnchor:
- 创建一个
LayoutAnchor(),保存在组件字段里; - 在触发器所在 Element 的
onMount中调用scope.layoutAnchor(anchor); - 在它的
scene中调用context.anchor(anchor, rect)报告位置; - 在 portal 的配置中写
anchored(anchor) { ... },即OverlayPlacement.Anchored。
下面是一个完整的颜色选择弹层:
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.surface:0.1.0
import scoop.graphics.*
import scoop.surface.InputArea
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.style.*
import scoop.ui.style.macos.macosTheme
class ColorPicker(scope: ComponentScope): Component(scope) {
private val theme = currentThemeSource()
private val open = state(false)
private val choice = state("none")
private val anchor = LayoutAnchor()
public override fun render(): View {
val open = this.open
val choice = this.choice
val anchor = this.anchor
val palette = this.theme.current.value.tokens.palette
// The trigger: an ordinary button wrapped by an element that publishes the anchor.
val trigger =
element(
anchor,
{ props, mount -> AnchorBox(props, mount) },
[button("Choose a color", { open.value = !open.value })]
)
// The layer content: a styled card whose blank area still counts as "inside".
val pick =
{
name: String ->
choice.value = name
open.value = false
}
val card =
styled(
frame(
column {
spacing = 6.0
label("Pick one")
row {
spacing = 6.0
button("Red", { pick("red") })
button("Green", { pick("green") })
button("Blue", { pick("blue") })
}
}
) {
// Layers get bounded constraints; give the card its own width.
width = Some(240.0)
padding = Some(Insets.all(12.0))
}
) {
style {
background = Some(Paint(palette.popover.background))
border = Some(Border.all(1.0, palette.border))
corners = Corners.all(10.0)
boxShadows = [BoxShadow(Point(0.0, 6.0), 10.0, 10.0, palette.shadow)]
}
}
val panel = element({ mount -> PanelArea(mount) }, [card])
val layer =
portal(open.binding(), panel) {
anchored(anchor) {
preferredSide = OverlaySide.Bottom
gap = 6.0
}
dismiss {
escape = true
outsidePress = OutsidePress.CloseAndConsume
}
}
val content =
column {
spacing = 12.0
row {
spacing = 12.0
alignment = CrossAlignment.Center
add(trigger)
label(f"Selected: ${choice.value}")
}
add(layer)
}
return frame(content) {
padding = Some(Insets.all(24.0))
alignment = Alignment(AxisAlignment.Start, AxisAlignment.Start)
style { background(Some(Paint(palette.background.background))) }
}
}
}
/** Passes its single child through and reports the child's rectangle as an anchor. */
class AnchorBox(private val props: Props<LayoutAnchor>, scope: ComponentScope): Element<Unit>(
scope
) {
public override fun onMount() {
scope.layoutAnchor(props.value)
}
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
Unit
> {
val child = context.measureChild(0L, constraints)
context.placeChild(0L, Point(0.0, 0.0))
return LayoutResult(child, Unit)
}
public override fun scene(context: SceneContext, layout: Unit) {
context.anchor(props.value, Rect(0.0, 0.0, context.size.width, context.size.height))
context.children()
}
}
/** Declares the panel's whole rectangle as an input area so clicks on padding stay inside. */
class PanelArea(scope: ComponentScope): Element<Unit>(scope) {
private var area: InputArea? = None
public override fun onMount() {
area = Some(scope.createArea())
scope.routeChildren(area!!)
}
public override fun measure(context: MeasureContext, constraints: Constraints): LayoutResult<
Unit
> {
val child = context.measureChild(0L, constraints)
context.placeChild(0L, Point(0.0, 0.0))
return LayoutResult(child, Unit)
}
public override fun scene(context: SceneContext, layout: Unit) {
context.place(area!!, Rect(0.0, 0.0, context.size.width, context.size.height))
context.children()
}
}
fun main() {
val source = ThemeSource(macosTheme(ThemeMode.Light))
context(source) {
runUiApplication("Popover", { scope -> ColorPicker(scope) })
}
}
scoop run ui-custom-popover.scoop --release

点击 Choose a color,下方出现带阴影的卡片;点击卡片空白处不会关闭,点击某个颜色后关闭并更新右侧文字;点击窗口其他位置或按 Escape 也会关闭。
示例中有两个很小但很常用的 Element:
AnchorBox原样测量、放置唯一的子项,并在 scene 中把自己的矩形报告为锚点。锚点使用当前的变换和裁剪换算到窗口坐标,不需要输入区域。PanelArea给卡片铺一个覆盖整个面板的输入区域,并用scope.routeChildren(area)让子项的事件经过它。“外部点击”按逻辑子树判断:点在面板的内边距上时,如果那里没有任何属于弹层的输入区域,就会被当成外部点击而关闭弹层。
portal 的常用配置:
- 定位:
anchored(anchor) { preferredSide; alignment; gap; viewportPadding; matchAnchorWidth };viewport { horizontal; vertical }在窗口中对齐(例如居中的对话框,这是默认值);atPoint(point) { ... }以窗口坐标定位,适合右键菜单。定位会先给内容有界的约束,再按实际尺寸在空间不足时翻转到另一侧或平移;弹层内的元素可以在 scene 中通过context.overlayLayout读取最终的bounds、anchor和side,例如用来画指向锚点的箭头。 - 关闭:
dismiss { escape = true; outsidePress = OutsidePress.CloseAndConsume },默认两者都不关闭。CloseAndContinue在关闭的同时让被点中的控件继续收到这次按下(只适用于非模态)。每次只关闭最上层的适用弹层。 - 其他:
onCloseRequest可以拒绝用户发起的关闭,onClosed在弹层真正移除后调用,transition配置进入/退出动画,anchorVisibility决定锚点被滚出视野时关闭、隐藏还是保持显示。
18.2 模态弹层
把 mode 设为 OverlayMode.Modal 就得到同窗口模态:打开时保存原焦点并屏蔽背景输入,Tab 只在弹层内循环;关闭后焦点回到原来的位置。focus { initialFocus = Some(handle) } 指定打开后聚焦的控件:
val layer =
portal(open.binding(), dialog) {
mode = OverlayMode.Modal
focus { initialFocus = Some(confirm) }
dismiss { escape = true }
}
这里 confirm 是一个 FocusHandle,通过 button("Delete", { ... }) { focus { handle = Some(confirm) } } 交给对话框中的按钮。遮罩、面板外观和布局都由你放进 dialog 的内容决定。另有 OverlayMode.FocusContained:焦点限制在弹层内,但不屏蔽背景的指针输入。
18.3 自定义滚动容器与按需列表
最后编写一个固定行高、一万行的列表。它同时演示两件事:用 ScrollViewport 实现滚动,用 LazyElement 只构建看得见的行。
//! dep: scoop:scoop.ui:0.1.0
//! dep: scoop:scoop.ui.component:0.1.0
//! dep: scoop:scoop.ui.style:0.1.0
//! dep: scoop:scoop.ui.style.macos:0.1.0
//! dep: scoop:scoop.graphics:0.1.0
//! dep: scoop:scoop.surface:0.1.0
import scoop.graphics.*
import scoop.surface.*
import scoop.ui.*
import scoop.ui.component.*
import scoop.ui.style.Insets
import scoop.ui.style.ThemeMode
import scoop.ui.style.ThemeSource
import scoop.ui.style.macos.macosTheme
val rowHeight = 32.0
/** A snapshot of the data: stable keys plus a way to build one row on demand. */
class RowSource(private val total: Long): ItemSource {
public override val count: Long get() = total
public override fun keyAt(index: Long): ViewKey = ViewKey.Number(index)
public override fun indexOfKey(key: ViewKey): Long? {
when (key) {
case Number(val value) -> {
if (value >= 0L && value < total)
return Some(value)
}
else -> {}
}
return None
}
public override fun build(index: Long): View =
frame(label(f"Row ${index + 1L}")) {
padding = Some(Insets(12.0, 0.0, 12.0, 0.0))
alignment = Alignment(AxisAlignment.Start, AxisAlignment.Center)
}
}
class ListDemo(scope: ComponentScope): Component(scope) {
private val scroll = ScrollState()
private val source = RowSource(10000L)
public override fun render(): View =
lazyElement(source, scroll, { props, mount -> FixedRows(props, mount) })
}
/** A vertical list with fixed row height that only builds the rows it can see. */
class FixedRows(private val props: Props<ScrollState>, scope: ComponentScope): LazyElement<
ScrollLayout
>(scope) {
private var viewport: ScrollViewport? = None
private var area: InputArea? = None
public override fun onMount() {
val view = scope.scrollViewport(props.value)
viewport = Some(view)
val region = scope.createArea()
area = Some(region)
// Wheel input that no row consumed ends up in this default action.
scope.resource {
region.scope.addDefaultAction {
current,
event -> when (event) {
case Pointer(InputPointerEvent.Wheel(_, _, _, _)) -> {
current.consumeScroll(rowHeight) {
amount ->
val used =
props.value.scrollBy(Point(0.0, -amount.y), ScrollOrigin.User)
Point(0.0, -used.y)
}
}
else -> {}
}
}
}
scope.routeChildren(area!!)
}
public override fun measure(
context: LazyMeasureContext,
constraints: Constraints
): LayoutResult<ScrollLayout> {
val size =
constraints.constrain(
Size(constraints.maxWidth ?: 320.0, constraints.maxHeight ?: 480.0)
)
val content = Size(size.width, context.itemCount.toDouble() * rowHeight)
val layout = viewport!!.layout(size, content)
val top = layout.snapshot.offset.y
val first = (top / rowHeight).toLong()
var last = ((top + size.height) / rowHeight).toLong()
if (last >= context.itemCount)
last = context.itemCount - 1L
val row = Constraints.tight(Size(size.width, rowHeight))
// Visible rows first, then rows the framework asks us to keep (focus, text sessions...).
var index = first
while (index <= last) {
context.measureItem(index, row)
context.placeItem(index, Point(0.0, index.toDouble() * rowHeight))
index += 1L
}
for (pinned in context.pinnedItems) {
if (pinned < first || pinned > last) {
context.measureItem(pinned, row)
context.placeItem(pinned, Point(0.0, pinned.toDouble() * rowHeight))
}
}
return LayoutResult(LayoutMetrics(size), layout)
}
public override fun scene(context: SceneContext, layout: ScrollLayout) {
val bounds = Rect(0.0, 0.0, context.size.width, context.size.height)
context.place(area!!, bounds)
context.draw { paint -> paint.canvas.clear(Color(0.97, 0.97, 0.98)) }
// present() clips to the viewport and shifts content by the scroll offset.
viewport!!.present(context, layout, Some { content -> content.children() })
}
}
fun main() {
val source = ThemeSource(macosTheme(ThemeMode.Light))
context(source) {
runUiApplication("Ten thousand rows", { scope -> ListDemo(scope) })
}
}
scoop run ui-custom-list.scoop --release
用滚轮或触控板滚动,行号连续变化;无论滚到哪里,任何时刻都只有可见的十几行被构建和挂载。
数据源:ItemSource。 它提供 count、keyAt(index)、indexOfKey(key) 和 build(index)。key 必须稳定且唯一(ViewKey.Text 或 ViewKey.Number);数据变化时换一个新的 ItemSource 快照。框架只对实际访问到的下标调用 build,不会预先构建全部行;已构建的行仅因滚动而重新测量时,也不会重跑 build。
按需容器:lazyElement(source, props, create) 与 LazyElement<L>。 生命周期和 scene 与 Element 相同,区别是 measure 收到 LazyMeasureContext:
context.itemCount是条目总数;context.measureItem(index, constraints)按需构建、挂载并测量第index项;context.placeItem(index, origin)放置它,之后本帧不能再测量或放置同一项;context.pinnedItems列出必须保留的条目,例如持有焦点、正在等待聚焦、正在被按下或拖动的行。即使它们滚出了可见范围,也要测量和放置,否则交互会被打断;视口裁剪会让它们不可见。
本帧没有被测量放置的条目会被卸载。第四个参数 retention 可以设为 ItemRetention.KeepAlive(maxOffscreenItems),额外保留若干个最近离开的实例,滚回来时复用它们的状态。
滚动:ScrollState 与 ScrollViewport。 ScrollState 是普通的业务对象,保存最近一次成功呈现的 offset、viewport、content 尺寸,提供 scrollTo、scrollBy、reveal 和 animateTo。自绘容器在 onMount 中用 scope.scrollViewport(state) 把它绑定到自己,然后:
- 在 measure 中调用
viewport.layout(viewportSize, contentSize),得到本帧的ScrollLayout,其中snapshot.offset是本帧使用的滚动位置。FixedRows 据此算出可见的行号范围; - 在 scene 中调用
viewport.present(context, layout, Some { content -> content.children() })。回调中的内容自动被裁剪到视口,并按滚动偏移平移;子项放在内容坐标中即可(第i行放在y = i × 行高)。滚动条等固定装饰画在回调之外。
滚轮输入要自己接:FixedRows 在区域的默认动作中处理 InputPointerEvent.Wheel,用 current.consumeScroll(lineStep) { amount -> ... } 把行或像素增量换算成位移,交给 state.scrollBy(delta, ScrollOrigin.User),并返回实际消耗的部分,剩余部分会继续交给外层的滚动容器。放在默认动作中,是为了让行内的子控件有机会先处理这次事件。
行高可变的容器常常在内容测量之后才知道应该滚到哪里,例如保持当前阅读位置不跳动。这时可以在布局中构造 ScrollAdjustment(state.requestRevision, offset) 作为 viewport.layout 的第三个参数:它只在定位意图仍是同一次请求时生效,新的滚动请求和正在进行的动画优先。
按 key 聚焦:scope.lazyFocus(viewport)。 对于没有构建的行,无法预先拿到它们的 FocusHandle。LazyElement 可以在 onMount 中登记 scope.lazyFocus(viewport, options),之后用 requestFocus(key, ItemFocusEdge.First) 请求聚焦某个 key 对应的行:对应条目会加入 pinnedItems,容器通过 pendingItem 得知需要先把它滚到可见位置。LazyFocusOptions 还可以让整个列表只占一个 Tab 停靠点、用方向键在行之间移动。控件库中的 VirtualList 就是这样实现的,需要完整的键盘行为时,直接使用它(见焦点、键盘与滚动)通常更合适。
常见错误与继续阅读
| 现象 | 原因与处理 |
|---|---|
| 运行时报不能在 measure/scene/draw 中写 State | 这些阶段必须是纯计算;在输入回调或 update()/onMount() 中修改状态 |
| 点击自绘区域没有反应 | 区域没有在 scene 中 context.place(area, rect),或处理器检查的阶段不对:作为目标的指针事件在 RoutedPhase.Target 阶段到达 |
| 悬停或焦点变化后画面不更新 | 这些变化不会触发 render;读取 scope.press(...).interaction,或在回调中调用 scope.requestFrame() |
| 内存或句柄持续增长 | 在 scene/draw 中创建了 Path、图片或 painter;改到 onMount 中用 scope.resource { } 登记 |
| 动画结束后窗口仍在持续重绘 | 在 draw 中调用了 animateTo 或 requestFrame();只在 update() 或输入回调中启动动画 |
| 子项没有显示 | measure 中测量了子项但忘记 placeChild,或 scene 中没有调用 children() |
drawLayer 显示旧内容 |
revision 没有覆盖所有影响像素的输入 |
ShaderProgram.compile 抛出 GraphicsException |
SkSL 源码有误,异常消息就是编译器诊断 |
绑定 uniform 时报 invalid shader binding |
名称或类型与程序中的 uniform 不一致,例如对 layout(color) uniform half4 用了 setFloat |
| 背景滤镜没有效果 | 要模糊的内容必须在同一图层中先于面板绘制;画在面板之后或其他图层中的内容不会被采样 |
在 builder 块中写 anchored(anchor)、label(...) 等时报 “implicit use of an outer receiver” 或类型为 Unit |
先把组件字段取到局部变量(val anchor = this.anchor);需要 View 值时在块外构造 |
| 点弹层的内边距也会关闭弹层 | 弹层面板没有覆盖整个面板的输入区域;像 PanelArea 那样创建区域并 routeChildren |
| 列表滚走后正在编辑或聚焦的行丢失状态 | 没有测量和放置 context.pinnedItems 中的条目 |
下一篇桌面集成与异步介绍菜单栏、托盘、多窗口和后台任务。本篇所用接口的完整合同见 Scoop 仓库的 UI 规范;工具链中的 scoop.ui/examples/custom 是一个只依赖框架的自绘 Counter,scoop.ui.component 的源码则展示了全部内置控件如何基于这些接口实现。以上示例在 macOS 上验证,Linux 上用法相同。