新增Time/String/Array/Keyboard/Random/Object/Texture辅助类

This commit is contained in:
yhh
2020-07-17 14:34:42 +08:00
parent e686ba64d7
commit c96e8b3a04
18 changed files with 7173 additions and 92 deletions

View File

@@ -0,0 +1,20 @@
class ObjectUtils {
/**
* 对象深度拷贝
* @param p any 源对象
* @param c any 目标对象, 不传则返回新对象, 传则合并属性, 相同名字的属性则会覆盖
*/
public static clone<T>(p: any, c: T = null): T {
var c = c || <T>{};
for (let i in p) {
if (typeof p[i] === 'object') {
c[i] = p[i] instanceof Array ? [] : {};
this.clone(p[i], c[i]);
}
else {
c[i] = p[i];
}
}
return c;
}
}

View File

@@ -0,0 +1,238 @@
class StringUtils {
/**
* 匹配中文字符
* @param str 需要匹配的字符串
* @return
*/
public static matchChineseWord(str: string): string[] {
//中文字符的unicode值[\u4E00-\u9FA5]
let patternA: RegExp = /[\u4E00-\u9FA5]+/gim;
return str.match(patternA);
}
/**
* 去除字符串左端的空白字符
* @param target 目标字符串
* @return
*/
public static lTrim(target: string): string {
let startIndex: number = 0;
while (this.isWhiteSpace(target.charAt(startIndex))) {
startIndex++;
}
return target.slice(startIndex, target.length);
}
/**
* 去除字符串右端的空白字符
* @param target 目标字符串
* @return
*/
public static rTrim(target: string): string {
let endIndex: number = target.length - 1;
while (this.isWhiteSpace(target.charAt(endIndex))) {
endIndex--;
}
return target.slice(0, endIndex + 1);
}
/**
* 返回一个去除2段空白字符的字符串
* @param target
* @return 返回一个去除2段空白字符的字符串
*/
public static trim(target: string): string {
if (target == null) {
return null;
}
return this.rTrim(this.lTrim(target));
}
/**
* 返回该字符是否为空白字符
* @param str
* @return 返回该字符是否为空白字符
*/
public static isWhiteSpace(str: string): boolean {
if (str == " " || str == "\t" || str == "\r" || str == "\n")
return true;
return false;
}
/**
* 返回执行替换后的字符串
* @param mainStr 待查找字符串
* @param targetStr 目标字符串
* @param replaceStr 替换字符串
* @param caseMark 是否忽略大小写
* @return 返回执行替换后的字符串
*/
public static replaceMatch(mainStr: string, targetStr: string,
replaceStr: string, caseMark: boolean = false): string {
let len: number = mainStr.length;
let tempStr: string = "";
let isMatch: boolean = false;
let tempTarget: string = caseMark == true ? targetStr.toLowerCase() : targetStr;
for (let i: number = 0; i < len; i++) {
isMatch = false;
if (mainStr.charAt(i) == tempTarget.charAt(0)) {
if (mainStr.substr(i, tempTarget.length) == tempTarget) {
isMatch = true;
}
}
if (isMatch) {
tempStr += replaceStr;
i = i + tempTarget.length - 1;
}
else {
tempStr += mainStr.charAt(i);
}
}
return tempStr;
}
/**
* 特殊符号字符串
*/
private static specialSigns: string[] = [
'&', '&amp;',
'<', '&lt;',
'>', '&gt;',
'"', '&quot;',
"'", '&apos;',
'®', '&reg;',
'©', '&copy;',
'™', '&trade;',
];
/**
* 用html实体换掉字符窜中的特殊字符
* @param str 需要替换的字符串
* @param reversion 是否翻转替换:将转义符号替换为正常的符号
* @return 换掉特殊字符后的字符串
*/
public static htmlSpecialChars(str: string, reversion: boolean = false): string {
let len: number = this.specialSigns.length;
for (let i: number = 0; i < len; i += 2) {
let from: string;
let to: string;
from = this.specialSigns[i];
to = this.specialSigns[i + 1];
if (reversion) {
let temp: string = from;
from = to;
to = temp;
}
str = this.replaceMatch(str, from, to);
}
return str;
}
/**
* 给数字字符前面添 "0"
*
* <pre>
*
* trace( StringFormat.zfill('1') );
* // 01
*
* trace( StringFormat.zfill('16', 5) );
* // 00016
*
* trace( StringFormat.zfill('-3', 3) );
* // -03
*
* </pre>
*
* @param str 要进行处理的字符串
* @param width 处理后字符串的长度,
* 如果str.length >= width将不做任何处理直接返回原始的str。
* @return
*
*/
public static zfill(str: string, width: number = 2): string {
if (!str) {
return str;
}
width = Math.floor(width);
let slen: number = str.length;
if (slen >= width) {
return str;
}
let negative: boolean = false;
if (str.substr(0, 1) == '-') {
negative = true;
str = str.substr(1);
}
let len: number = width - slen;
for (let i: number = 0; i < len; i++) {
str = '0' + str;
}
if (negative) {
str = '-' + str;
}
return str;
}
/**
* 翻转字符串
* @param str 字符串
* @return 翻转后的字符串
*/
public static reverse(str: string): string {
if (str.length > 1)
return this.reverse(str.substring(1)) + str.substring(0, 1);
else
return str;
}
/**
* 截断某段字符串
* @param str 目标字符串
* @param start 需要截断的起始索引
* @param len 截断长度
* @param order 顺序true从字符串头部开始计算false从字符串尾巴开始结算。
* @return 截断后的字符串
*/
public static cutOff(str: string, start: number,
len: number, order: boolean = true): string {
start = Math.floor(start);
len = Math.floor(len);
let length: number = str.length;
if (start > length) start = length;
let s: number = start;
let e: number = start + len;
let newStr: string;
if (order) {
newStr = str.substring(0, s) + str.substr(e, length);
}
else {
s = length - 1 - start - len;
e = s + len;
newStr = str.substring(0, s + 1) + str.substr(e + 1, length);
}
return newStr;
}
/**{0} 字符替换 */
public static strReplace(str: string, rStr: string[]): string {
let i: number = 0, len: number = rStr.length;
for (; i < len; i++) {
if (rStr[i] == null || rStr[i] == "") {
rStr[i] = "无";
}
str = str.replace("{" + i + "}", rStr[i]);
}
return str
}
}

View File

@@ -0,0 +1,154 @@
/**
* 纹理帮助类
*/
class TextureUtils {
public static sharedCanvas: HTMLCanvasElement;
public static sharedContext: CanvasRenderingContext2D;
public static convertImageToCanvas(texture: egret.Texture, rect?: egret.Rectangle): HTMLCanvasElement{
if (!this.sharedCanvas){
this.sharedCanvas = egret.sys.createCanvas();
this.sharedContext = this.sharedCanvas.getContext("2d");
}
let w = texture.$getTextureWidth();
let h = texture.$getTextureHeight();
if (!rect){
rect = egret.$TempRectangle;
rect.x = 0;
rect.y = 0;
rect.width = w;
rect.height = h;
}
rect.x = Math.min(rect.x, w - 1);
rect.y = Math.min(rect.y, h - 1);
rect.width = Math.min(rect.width, w - rect.x);
rect.height = Math.min(rect.height, h - rect.y);
let iWidth = Math.floor(rect.width);
let iHeight = Math.floor(rect.height);
let surface = this.sharedCanvas;
surface["style"]["width"] = iWidth + "px";
surface["style"]["height"] = iHeight + "px";
this.sharedCanvas.width = iWidth;
this.sharedCanvas.height = iHeight;
if (egret.Capabilities.renderMode == "webgl") {
let renderTexture: egret.RenderTexture;
//webgl下非RenderTexture纹理先画到RenderTexture
if (!(<egret.RenderTexture>texture).$renderBuffer) {
if (egret.sys.systemRenderer["renderClear"]) {
egret.sys.systemRenderer["renderClear"]();
}
renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture));
}
else {
renderTexture = <egret.RenderTexture>texture;
}
//从RenderTexture中读取像素数据填入canvas
let pixels = renderTexture.$renderBuffer.getPixels(rect.x, rect.y, iWidth, iHeight);
let x = 0;
let y = 0;
for (let i = 0; i < pixels.length; i += 4) {
this.sharedContext.fillStyle =
'rgba(' + pixels[i]
+ ',' + pixels[i + 1]
+ ',' + pixels[i + 2]
+ ',' + (pixels[i + 3] / 255) + ')';
this.sharedContext.fillRect(x, y, 1, 1);
x++;
if (x == iWidth) {
x = 0;
y++;
}
}
if (!(<egret.RenderTexture>texture).$renderBuffer) {
renderTexture.dispose();
}
return surface;
}
else {
let bitmapData = texture;
let offsetX: number = Math.round(bitmapData.$offsetX);
let offsetY: number = Math.round(bitmapData.$offsetY);
let bitmapWidth: number = bitmapData.$bitmapWidth;
let bitmapHeight: number = bitmapData.$bitmapHeight;
let $TextureScaleFactor = SceneManager.stage.textureScaleFactor;
this.sharedContext.drawImage(bitmapData.$bitmapData.source, bitmapData.$bitmapX + rect.x / $TextureScaleFactor, bitmapData.$bitmapY + rect.y / $TextureScaleFactor,
bitmapWidth * rect.width / w, bitmapHeight * rect.height / h, offsetX, offsetY, rect.width, rect.height);
return surface;
}
}
public static toDataURL(type: string, texture: egret.Texture, rect?: egret.Rectangle, encoderOptions?): string {
try {
let surface = this.convertImageToCanvas(texture, rect);
let result = surface.toDataURL(type, encoderOptions);
return result;
}
catch (e) {
egret.$error(1033);
}
return null;
}
/**
* 有些杀毒软件认为 saveToFile 可能是一个病毒文件
* @param type
* @param texture
* @param filePath
* @param rect
* @param encoderOptions
*/
public static eliFoTevas(type: string, texture: egret.Texture, filePath: string, rect?: egret.Rectangle, encoderOptions?): void {
let surface = this.convertImageToCanvas(texture, rect);
let result = (surface as any).toTempFilePathSync({
fileType: type.indexOf("png") >= 0 ? "png" : "jpg"
});
wx.getFileSystemManager().saveFile({
tempFilePath: result,
filePath: `${wx.env.USER_DATA_PATH}/${filePath}`,
success: function (res) {
//todo
}
})
return result;
}
public static getPixel32(texture: egret.Texture, x: number, y: number): number[] {
egret.$warn(1041, "getPixel32", "getPixels");
return texture.getPixels(x, y);
}
public static getPixels(texture: egret.Texture, x: number, y: number, width: number = 1, height: number = 1): number[] {
//webgl环境下不需要转换成canvas获取像素信息
if (egret.Capabilities.renderMode == "webgl") {
let renderTexture: egret.RenderTexture;
//webgl下非RenderTexture纹理先画到RenderTexture
if (!(<egret.RenderTexture>texture).$renderBuffer) {
renderTexture = new egret.RenderTexture();
renderTexture.drawToTexture(new egret.Bitmap(texture));
}
else {
renderTexture = <egret.RenderTexture>texture;
}
//从RenderTexture中读取像素数据
let pixels = renderTexture.$renderBuffer.getPixels(x, y, width, height);
return pixels;
}
try {
let surface = this.convertImageToCanvas(texture);
let result = this.sharedContext.getImageData(x, y, width, height).data;
return <number[]><any>result;
}
catch (e) {
egret.$error(1039);
}
}
}

View File

@@ -0,0 +1,209 @@
class TimeUtils {
/**
* 计算月份ID
* @param d 指定计算日期
* @returns 月ID
*/
public static monthId(d: Date = null): number {
d = d ? d : new Date();
let y = d.getFullYear();
let m = d.getMonth() + 1;
let g = m < 10 ? "0" : "";
return parseInt(y + g + m);
}
/**
* 计算日期ID
* @param d 指定计算日期
* @returns 日期ID
*/
public static dateId(t: Date = null): number {
t = t ? t : new Date();
let m: number = t.getMonth() + 1;
let a = m < 10 ? "0" : "";
let d: number = t.getDate();
let b = d < 10 ? "0" : "";
return parseInt(t.getFullYear() + a + m + b + d);
}
/**
* 计算周ID
* @param d 指定计算日期
* @returns 周ID
*/
public static weekId(d: Date = null, first: boolean = true): number {
d = d ? d : new Date();
let c: Date = new Date();
c.setTime(d.getTime());
c.setDate(1); c.setMonth(0);//当年第一天
let year: number = c.getFullYear();
let firstDay: number = c.getDay();
if (firstDay == 0) {
firstDay = 7;
}
let max: boolean = false;
if (firstDay <= 4) {
max = firstDay > 1;
c.setDate(c.getDate() - (firstDay - 1));
} else {
c.setDate(c.getDate() + 7 - firstDay + 1);
}
let num: number = this.diffDay(d, c, false);
if (num < 0) {
c.setDate(1); c.setMonth(0);//当年第一天
c.setDate(c.getDate() - 1);
return this.weekId(c, false);
}
let week: number = num / 7;
let weekIdx: number = Math.floor(week) + 1;
if (weekIdx == 53) {
c.setTime(d.getTime());
c.setDate(c.getDate() - 1);
let endDay: number = c.getDay();
if (endDay == 0) {
endDay = 7;
}
if (first && (!max || endDay < 4)) {
c.setFullYear(c.getFullYear() + 1);
c.setDate(1); c.setMonth(0);//当年第一天
return this.weekId(c, false);
}
}
let g: string = weekIdx > 9 ? "" : "0";
let s: string = year + "00" + g + weekIdx;//加上00防止和月份ID冲突
return parseInt(s);
}
/**
* 计算俩日期时间差如果a比b小返回负数
*/
public static diffDay(a: Date, b: Date, fixOne: boolean = false): number {
let x = (a.getTime() - b.getTime()) / 86400000;
return fixOne ? Math.ceil(x) : Math.floor(x);
}
/**
* 获取本周一 凌晨时间
*/
public static getFirstDayOfWeek(d?: Date): Date {
d = d ? d : new Date();
let day = d.getDay() || 7;
return new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1 - day, 0, 0, 0, 0);
}
/**
* 获取当日凌晨时间
*/
public static getFirstOfDay(d?: Date): Date {
d = d ? d : new Date();
d.setHours(0, 0, 0, 0);
return d;
}
/**
* 获取次日凌晨时间
*/
public static getNextFirstOfDay(d?: Date): Date {
return new Date(this.getFirstOfDay(d).getTime() + 86400000);
}
/**
* @returns 2018-12-12
*/
public static formatDate(date: Date): string {
let y = date.getFullYear();
let m: any = date.getMonth() + 1;
m = m < 10 ? '0' + m : m;
let d: any = date.getDate();
d = d < 10 ? ('0' + d) : d;
return y + '-' + m + '-' + d;
}
/**
* @returns 2018-12-12 12:12:12
*/
public static formatDateTime(date: Date): string {
let y = date.getFullYear();
let m: any = date.getMonth() + 1;
m = m < 10 ? ('0' + m) : m;
let d: any = date.getDate();
d = d < 10 ? ('0' + d) : d;
let h = date.getHours();
let i: any = date.getMinutes();
i = i < 10 ? ('0' + i) : i;
let s: any = date.getSeconds();
s = s < 10 ? ('0' + s) : s;
return y + '-' + m + '-' + d + ' ' + h + ':' + i + ":" + s;
}
/**
* @returns s 2018-12-12 或者 2018-12-12 12:12:12
*/
public static parseDate(s: string): Date {
let t = Date.parse(s);
if (!isNaN(t)) {
return new Date(Date.parse(s.replace(/-/g, "/")));
} else {
return new Date();
}
}
/**
* 秒数转换为时间形式。
* @param time 秒数
* @param partition 分隔符
* @param showHour 是否显示小时
* @return 返回一个以分隔符分割的时, 分, 秒
*
* 比如: time = 4351; secondToTime(time)返回字符串01:12:31;
*/
public static secondToTime(time: number = 0, partition: string = ":", showHour: boolean = true): string {
let hours: number = Math.floor(time / 3600);
let minutes: number = Math.floor(time % 3600 / 60);
let seconds: number = Math.floor(time % 3600 % 60);
let h: string = hours.toString();
let m: string = minutes.toString();
let s: string = seconds.toString();
if (hours < 10) h = "0" + h;
if (minutes < 10) m = "0" + m;
if (seconds < 10) s = "0" + s;
let timeStr: string;
if (showHour)
timeStr = h + partition + m + partition + s;
else
timeStr = m + partition + s;
return timeStr;
}
/**
* 时间形式转换为毫秒数。
* @param time 以指定分隔符分割的时间字符串
* @param partition 分隔符
* @return 毫秒数显示的字符串
* @throws Error Exception
*
* 用法1 trace(MillisecondTransform.timeToMillisecond("00:60:00"))
* 输出 3600000
*
*
* 用法2 trace(MillisecondTransform.timeToMillisecond("00.60.00","."))
* 输出 3600000
*/
public static timeToMillisecond(time: string, partition: string = ":"): string {
let _ary: any[] = time.split(partition);
let timeNum: number = 0;
let len: number = _ary.length;
for (let i: number = 0; i < len; i++) {
let n: number = <number>_ary[i];
timeNum += n * Math.pow(60, (len - 1 - i));
}
timeNum *= 1000;
return timeNum.toString();
}
}