1

So I've searched through the SO for half an hour and couldn't find answer.

I have to render picture where user can dinamically enter the font size, picture dimension and message. That message has to be vertically and horizontally centrally aligned over the picutre. I just can't get it right, it would be ok if the text is short, but user can enter anything in URL (example):

http://localhost:8080/app/slika?size=16&dim=100x200&msg=Java%20rulesfaekofakoefaeofae

Back-end is done by JSP and Java, here is the code of jsp file:

<body>
<div>
    <img src="fruits.png" width="${ width }" height="${ height }" style="vertical-align: middle">
    <%
        int centerWidth = (Integer) request.getAttribute("width") / 2;
        int centerHeight = (Integer) request.getAttribute("height") / 2;
    %>

    <span
        STYLE="position:absolute; left:<%= centerWidth/2 %>; top:<%=centerHeight %>; 
        text-align:center; font-size:${ fontSize }px; width=100%">${ message }
    </span>
</div>

You can see that I "kinda" hardcoded it, so for short messages the display will be fine, but for long it won't (as the text will go over the image, and it should break into next line).

That last sentence is what is bothering me, how to break text into the next line? I managed to align it, but can't break it.

stevenw00
  • 1,155
  • 1
  • 13
  • 22
danchy
  • 447
  • 2
  • 7
  • 18

2 Answers2

0

You can actually just use CSS to display any arbitary text over any arbitary size of image (without hardcoding).

.box { 
  position: relative;
  float: left;
}

.text {
  width: 100%;
  text-align: center;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  /* Custom */
  color: red;
  font-weight: bold;
  font-size: 20px;
}
<div class="box">
  <img src="https://placeimg.com/300/300/nature">
  <div class="text">Lorem Ipsum</div>
</div>

<div class="box">
  <img src="https://placeimg.com/300/300/nature">
  <div class="text">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin pretium non diam vel fermentum.</div>
</div>
stevenw00
  • 1,155
  • 1
  • 13
  • 22
-1

You can use a table with one cell or a div with display: table-cell inside a div with display: table. Cell can be center-aligned horizontally and vertically and have a background with your image.

Here's my example: http://www.kamil256.master.pl/img_center_text_example.html

CSS:

table {
    border-collapse: collapse;
    width: 400px; /* width which you get from user */
    height: 300px; /* height which you get from user */
}
td {
    background: url("cat.png") top left no-repeat;
    background-size: 100% 100%;
    font: 14px; /* font size which you get from user */
    text-align: center;
}

HTML:

<table>
    <td><!-- text which you get from user -->
        http://localhost:8080/app/slika?size=16&dim=100x200&msg=Java%20rulesfaekofakoefaeofae
    </td>
</table>
alcohol is evil
  • 686
  • 12
  • 34