在SpreadJS自定义单元格系列-RadioButton单元格之一中我们已经实现了Radio Button的基本功能。同时,我们也实现了对Cell设置字体,对齐方式,页面缩放等功能,这里我们继续优化Cell Type,使之支持背景色设置,支持列宽行宽自动调整,支持json导入导出。
1. 设置背景色
设置背景色可以通过canvas直接填充设置,但是我们也可以在paint方法中调用CustomCellType的paint方法传递空字符串,快速实现背景色的绘制
GcSpread.Sheets.CustomCellType.prototype.paint.call(this, ctx, '', x, y, w, h, style, options);
2. 重写getAutoFitHeight和getAutoFitWidth 方法,实现行高列宽自适应
这里需要注意spread的zoom缩放
RaidoButtonCellType.prototype.getAutoFitWidth = function (value, text, cellStyle, zoomFactor, context) {if(this._isHorizontal){return (this._sumItemTextWidth + this._size * zoomFactor * this._items.length) / zoomFactor;}else{
return (this._maxItemTextWidth + this._size * zoomFactor) / zoomFactor;}}RaidoButtonCellType.prototype.getAutoFitHeight = function (value, text, cellStyle, zoomFactor, context) {if(this._isHorizontal){return this._size;}else{
return this._size * this._items.length;}}
3. 实现toJSON和fromJSON是单元格支持json导入导出
在SpreadJS中文学习指南中有详细介绍如何实现自定义特性序列化,一般情况下我们只需要设置typeName即可实现此功能,SpreadJS会自动将CellType的属性保存,我们也可以自己实现toJSON和fromJSON。
RaidoButtonCellType.prototype._isDefaultValue = function(propertyName, value){switch (propertyName)
{case"isHorizontal":return value === false;case"items":return value === [];
case"size":return value === 22;
default:
return false}};RaidoButtonCellType.prototype.toJSON = function(){var self = this;var dictData = {
typeName: self.typeName,
isHorizontal: self.isHorizontal(),
items: self.items(),
size: self.size(),
};var settings = {};
for (var item in dictData){var value = dictData[item];
if (!self._isDefaultValue(item, value)){settings[item] = value}}return settings
};RaidoButtonCellType.prototype.fromJSON = function(settings, isNoneSchema){if (!settings)
{return
}if (settings.isHorizontal !== null && settings.isHorizontal !== undefined){this.isHorizontal(settings.isHorizontal)
}if (settings.items !== null && settings.items !== undefined){this.items(settings.items)
}if (settings.size !== null && settings.size !== undefined){this.size(settings.size)
}};
到此,我们的CellType已经可以在不同场合下通用。
RunJS地址:http://runjs.cn/detail/evyclttm
更多资源
SpreadJS中文学习指南:http://demo.grapecity.com.cn/SpreadJS/TutorialSample/#/samples
SpreadJS在线英文产品文档:http://sphelp.grapecity.com/webhelp/SpreadJSWeb/webframe.html#welcome.html
如果您对SpreadJS产品感兴趣,可以到官方网站下载试用:/developer/spreadjs
如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn