drawString not working for EditorCustomElementRenderer

Answered

Hello,

I am having problems adding a custom inlay to the editor. When using the following method, only an empty inlay is added without any text at the beginning of the editor (s. Screenshot). What am I doing wrong? I saw in other examples that it should work. I am using Intellij IDEA 2022.2.

textEditor.getInlayModel().addInlineElement(0, new EditorCustomElementRenderer() {
@Override
public int calcWidthInPixels(@NotNull Inlay inlay) {
return 50;
}

@Override
public int calcHeightInPixels(@NotNull Inlay inlay) {
return 50;
}

@Override
public void paint(@NotNull Inlay inlay, @NotNull Graphics g, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {
Editor editor = inlay.getEditor();
g.setColor(JBColor.GRAY);
g.setFont(getFont(editor));
g.drawString("HELP", targetRegion.x, targetRegion.y);
}
});

4 comments
Comment actions Permalink

Hi,

I don’t understand the full context. Could you please explain your use case? It doesn’t seem that you implement com.intellij.codeInsight.inlayProvider extension point. Is there any reason for that? Please see https://plugins.jetbrains.com/docs/intellij/inlay-hints.html#advanced-inlay-hints for example implementations.

0
Comment actions Permalink

Thanks for the reply. I am developing a custom plugin which displays code coverage information. Therefore, it should be possible to insert inlay hints at specific positions in different colors. I first tried implementing the extension point. However, I couldn't find an option to reload the inlay information at a specific user action. Hence, I tried implementing it via the textEditor. Is there a better way to do this?

I also found the problem I was having. Apparently, the inlay hint is displayed above the corresponding line when implementing it this way. So one needs to add to the y axis of the target region to have it displayed (especially when it is in the first line).

0
Comment actions Permalink

Hi,

`Graphics.drawString` expects Y coordinate of the text baseline to be passed, and you're passing the coordinate of the top inlay's border - that's why your text is displayed 'above' the target region. Correct Y to pass depends on what you want to achieve, but if you need the text you draw to be aligned vertically with the text in editor, pass `targetRegion.y + editor.getAscent()` as Y.

0
Comment actions Permalink

Great thanks!

0

Please sign in to leave a comment.