Posted by
Johannes Weissmann on
Jun 15, 2011; 2:41pm
URL: http://imagej.273.s1.nabble.com/Filled-Background-when-drawing-a-string-tp3684237p3684240.html
On 14.06.2011 04:17, Rasband, Wayne (NIH/NIMH) [E] wrote:
>> Hi Wayne,
>> I have already a working version using a text ROI and getting the
>> bounding box, so don't waste time on that.
>> I was simply wondering if I there is a build-in function to set the
>> background color for a string. My impression is that creating a text
>> ROI, getting bounding boxes is maybe a little overhead for such a
>> simple task. Especially since I was working with the java.Font classes
>> which leads to some awkward lines of code (e.g. there's no method to
>> set the font that takes a java.Font as argument).
>
> There is no built-in function to draw a string with a background.
>
> I got the JavaScript example working. It's at
>
>
http://imagej.nih.gov/ij/macros/js/DrawTextWithBackground.js>
> It should be easy to convert the function in the example to Java.
>
>> I am pretty new to ImageJ and not full professional software engineer,
>> but if there is some need I'd be happy to contribute some of my
>> developments.
>
> It would be helpful to have an example that draws a string with background using TextRois.
>
> Best regards,
>
> -wayne
>
>
>
Hi,
I implemented the following solution now. I run into some trouble even
with the TextROI method. The bounding rectangle (bounds() ) was always
only 1px wide and high.
/**
* Draws a string at the specified location with a filled
* background.
* @param ip
* @param string
* @param x
* @param y
* @param value Color value for the string.
*/
private void drawString(ImageProcessor ip, String string, int
x, int y, double value) {
Font font = new Font(Font.MONOSPACED, Font.PLAIN, 13);
// ip needs a function getJustification!
ip.setJustification(ImageProcessor.CENTER_JUSTIFY);
//Rectangle bounds = text.getBounds();
//ip.drawRect(x, y, bounds.width, bounds.height); // ->
// width&height == 1 ???
Graphics g = ip.getBufferedImage().getGraphics();
FontMetrics metrics = g.getFontMetrics(font);
int width = ip.getStringWidth(string);
int height = metrics.getAscent();
Roi roi = new Roi((int) x-(width/2), y-height, width,
height);
ip.setColor(Color.BLACK);
ip.fill(roi);
//ip.drawRect((int) x-(width/2), y-height, width,
height);
ip.setValue(value);
ip.drawString(string, x, y);
}
Cheers, Jo
--
Johannes Weissmann
Nedre Ferstadveg 26 | 7023 Trondheim
mail:
[hidden email]
fon: +47 45 124 191
"The truth, as always, will be far stranger." [Sir Arthur C. Clarke]