Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix text horizontal and vertical alignment error #772

Merged
merged 9 commits into from
Jun 2, 2022
3 changes: 1 addition & 2 deletions packages/core/src/2d/sprite/Sprite.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,8 +112,7 @@ export class Sprite extends RefObject {

set pivot(value: Vector2) {
const pivot = this._pivot;
const x = MathUtil.clamp(value.x, 0, 1);
const y = MathUtil.clamp(value.y, 0, 1);
const { x, y } = value;
if (pivot === value || pivot.x !== x || pivot.y !== y) {
pivot.setValue(x, y);
this._setDirtyFlagTrue(DirtyFlag.positions);
Expand Down
18 changes: 17 additions & 1 deletion packages/core/src/2d/text/TextRenderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,23 @@ export class TextRenderer extends Renderer {
const { width, height } = trimData;
const canvas = TextUtils.updateCanvas(width, height, trimData.data);
this._clearTexture();
const { _sprite: sprite } = this;
const { _sprite: sprite, horizontalAlignment } = this;

// Handle the case that width of text is larger than real width.
const originWidthInPixel = this.width * sprite.pixelsPerUnit;
const pivot = sprite.pivot;
if (originWidthInPixel > width && horizontalAlignment !== TextHorizontalAlignment.Center) {
const diffWidth = (originWidthInPixel - width) * 0.5;
if (horizontalAlignment === TextHorizontalAlignment.Left) {
pivot.x = 0.5 + diffWidth / width;
} else {
pivot.x = 0.5 - diffWidth / width;
}
} else {
pivot.x = 0.5;
}
sprite.pivot = pivot;

// If add fail, set texture for sprite.
cptbtptpbcptdtptp marked this conversation as resolved.
Show resolved Hide resolved
if (!this.engine._dynamicTextAtlasManager.addSprite(sprite, canvas)) {
const texture = new Texture2D(this.engine, width, height);
Expand Down