您可以替换内置的注释图标。例如,您可能希望评论的弹出式气泡看起来有所不同。
如需替换评论图标,请扩展 CommentIcon
,替换 ICommentIcon
中的所选方法,并注册新图标。
Extend CommentIcon
首先,将 CommentIcon
延长。
class MyCommentIcon extends Blockly.icons.CommentIcon {
constructor(sourceBlock) {
super(sourceBlock);
}
}
替换 ICommentIcon 和 Icon 中的方法
如需自定义图标,您可以替换 ICommentIcon
中的方法(如下各部分中所述)和 Blockly.icons.Icon
(如创建自定义图标中所述)。
请勿替换 getType
,该方法必须返回 Blockly.icons.IconType.COMMENT
。
文本
ICommentIcon
接口要求评论包含文本。
getText
方法必须返回评论的文本。setText
方法必须设置评论的文本并更新所有视觉元素。
getText() {
return this.text;
}
setText(text) {
this.text = text;
this.myRenderMethod();
}
气泡框
自定义评论图标必须实现 IHasBubble
接口才能支持序列化。即使您的图标在技术上没有气泡,您也应将可见性信息存储在类中,以便保持已保存的状态。否则,如果您加载包含评论是否处于打开状态的保存,则会丢失用户的信息。
bubbleIsVisible() {
return this.bubbleVisible;
}
setBubbleVisible(visible: boolean) {
this.bubbleVisible = visible;
}
如需详细了解气泡,请参阅使用弹出式气泡。
ICommentIcon
接口需要一个返回大小的 getBubbleSize
方法和一个设置大小的 setBubbleSize
方法。即使您的图标在技术上没有气泡,保存状态的相同推理也适用于此处。
getBubbleSize() {
return this.bubbleSize;
}
setBubbleSize(size) {
this.bubbleSize = size;
this.myRenderMethod();
}
ICommentIcon
还要求具有 getBubbleLocation
和 setBubbleLocation
方法,用于获取和设置工作区中气泡的位置。
setBubbleLocation(location) {
this.bubbleLocation = location;
}
getBubbleLocation() {
return this.bubbleLocation;
}
保存和加载
自定义评论图标必须实现 ISerializable
接口。状态应符合 CommentState
接口。
saveState() {
return {
text: this.text,
pinned: this.bubbleVisible,
height: this.bubbleSize.height,
width: this.bubbleSize.width,
x: this.bubbleLocation.x,
y: this.bubbleLocation.y,
}
}
loadState(state) {
this.setText(state.text);
this.setBubbleVisible(state.pinned);
this.setBubbleSize(new Blockly.utils.Size(state.width, state.height));
this.setBubbleLocation(new Blockly.utils.Coordinate(state.x, state.y));
}
如需详细了解图标序列化,请参阅保存和加载图标。
注册图标
最后,取消注册现有注释图标,并注册您的注释图标,以便 Blockly 可以实例化该图标。使用字符串 'comment'
进行取消注册,使用 IconTypes.COMMENT
进行注册。
Blockly.icons.registry.unregister('comment');
Blockly.icons.registry.register(Blockly.icons.IconType.COMMENT, myCommentIcon);
注册图标后,Blockly 会使用该图标来代替内置的注释图标,例如当用户点击上下文菜单中的“添加注释”或您调用 myBlock.setCommentText()
时。