import { SObjectItem } from "./SObjectItem"; import { SPainter, SRect, SSize } from "@saga-web/draw/lib"; import { SImageShowType } from "../enums/SImageShowType"; import { SGraphItem } from "../SGraphItem"; /** * 图片item * * @author 张宇(taohuzy@163.com) */ export class SImageItem extends SObjectItem { /** 图片dom */ img: CanvasImageSource | undefined; /** 展示模式 */ private _showType: SImageShowType = SImageShowType.Full; get showType(): SImageShowType { return this._showType; } set showType(v: SImageShowType) { this._showType = v; this.update(); } /** 图片地址 */ private _url: string = ""; get url(): string { return this._url; } set url(v: string) { this._url = v; this.img = new Image(); this.img.src = v; this.img.onload = (): void => { this.update(); }; } /** * 构造函数 * * @param parent 指向父Item * @param url 图片地址 */ constructor(parent: SGraphItem | null, url?: string) { super(parent); if (url) this.url = url; } // Constructor /** * Item对象边界区域 * * @return SRect */ boundingRect(): SRect { return new SRect( -this.width / 2, -this.height / 2, this.width, this.height ); } // Function boundingRect() /** * 宽高发发生变化 * * @param oldSize 改之前的大小 * @param newSize 改之后大小 * */ protected onResize(oldSize: SSize, newSize: SSize): void { this.update(); } // Function onResize() /** * Item绘制操作 * * @param painter 绘画类 */ onDraw(painter: SPainter): void { if (this.img) { // 要绘制图片的宽度 let width: number = 0; // 要绘制图片的宽度 let height: number = 0; // 图片item的宽高比 let itemAspectRatio: number = this.width / this.height; // 原始图片的宽高比 let imgAspectRatio: number = (this.img.width as number) / (this.img.height as number); // 原始图片的高宽比 let imgHwRatio: number = (this.img.height as number) / (this.img.width as number); if (this.showType == SImageShowType.Full) { width = this.width; height = this.height; } else if (this.showType == SImageShowType.Equivalency) { if (itemAspectRatio > imgAspectRatio) { height = this.height; width = imgAspectRatio * height; } else if (itemAspectRatio < imgAspectRatio) { width = this.width; height = width * imgHwRatio; } else { width = this.width; height = this.height; } } else if (this.showType == SImageShowType.AutoFit) { this.width = this.img.width as number; this.height = this.img.height as number; width = this.width; height = this.height; } painter.drawImage(this.img, -width / 2, -height / 2, width, height); } } // Function onDraw() } // Class SImageItem