public class CustomScreen extends HandledScreen<CustomScreenHandler> {
private static final Identifier VillagerChat = new Identifier(TheClassicofMountainsandOceans.MOD_ID, "textures/gui/villagerchat.png");
private static final int ImageWidth = 176;
private static final int ImageHeight = 222;
public CustomScreen(CustomScreenHandler handler, PlayerInventory inventory, Text title) {
super(handler, inventory, title);
this.backgroundWidth = ImageWidth;
this.backgroundHeight = ImageHeight;
}
@Override
protected void init() {
super.init();
// this.addDrawableChild(ButtonWidget.builder(Text.literal("Close"), (button) -> {
// this.client.setScreen(null);
// }).dimensions((this.width - this.backgroundWidth) / 2 + (this.backgroundWidth / 2 - 50), (this.height - this.backgroundHeight) / 2 + this.backgroundHeight - 30, 100, 20).build());
}
@Override
public void render(DrawContext context, int mouseX, int mouseY, float delta) {
this.renderBackground(context);
super.render(context, mouseX, mouseY, delta);
this.drawMouseoverTooltip(context, mouseX, mouseY);
}
@Override
protected void drawBackground(DrawContext context, float delta, int mouseX, int mouseY) {
RenderSystem.setShaderTexture(0, VillagerChat);
int i = (this.width - this.backgroundWidth) / 2;
int j = (this.height - this.backgroundHeight) / 2 -10;
context.drawTexture(VillagerChat, i, j, 0, 0, this.backgroundWidth, this.backgroundHeight);
}
@Override
protected void drawForeground(DrawContext context, int mouseX, int mouseY) {
Text title = Text.translatable("gui.como.conversation");
int titleX = (this.backgroundWidth - this.textRenderer.getWidth(title)) / 2;
int titleY = 10;
context.drawText(this.textRenderer, title, titleX, titleY, 4210752, false);
}
}
init在畫面初始化時會被呼叫,這個註解的部份是我原本打算做的畫面關閉按鈕,因為暫時不需要了所以註解起來。
render方法負責將繪製畫面上的元素,這個方法會持續執行,確保畫面保持更新,renderBackground方法繪製整個背景的底色,確保畫面一致。
super.render(context, mouseX, mouseY, delta)完成畫面的其他UI元素的繪製工作,例如物品欄
this.drawMouseoverTooltip(context, mouseX, mouseY)用來繪製滑鼠在某個物品上的時候出現的提示。
drawBackground方法中
RenderSystem.setShaderTexture(0, VillagerChat)設定了目前要繪製的材質,也就是我們之前定義的GUI照片。
i = (this.width - this.backgroundWidth) / 2 計算了GUI在畫面中的位置,確保畫面居中。
j = (this.height - this.backgroundHeight) / 2 - 10則確保畫面在中間偏上的位置。
drawForeground則負責畫面的標題文字
title我們使用translatable來讓文字可以隨語言轉換,同時也定義了標題在畫面的位置