Framebuffer wrap text

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
mcauser
Posts: 507
Joined: Mon Jun 15, 2015 8:03 am

Framebuffer wrap text

Post by mcauser » Sat Feb 24, 2018 1:42 am

I created a method for writing wrapped text to a Framebuffer, used with my e-paper displays.
Seems like it could be useful to add an optimised version to the Framebuffer class.

Code: Select all

def text_wrap(str,x,y,color,w,h,border=None):
	# optional box border
	if border is not None:
		fb.rect(x, y, w, h, border)
	cols = w // 8
	# for each row
	j = 0
	for i in range(0, len(str), cols):
		# draw as many chars fit on the line
		fb.text(str[i:i+cols], x, y + j, color)
		j += 8
		# dont overflow text outside the box
		if j >= h:
			break
eg.

Code: Select all

import framebuf
buf = bytearray(128 * 296 // 8)
fb = framebuf.FrameBuffer(buf, 128, 296, framebuf.MONO_HLSB)
black = 0
white = 1

str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam vel neque in elit tristique vulputate at et dui.'
# box position and dimensions
box_x = 8
box_y = 8
box_w = 112 # 14 cols
box_h = 112 # 14 rows (196 chars in total)
# colours
text_col = black
border_col = black
text_wrap(str, box_x, box_y, text_col, box_w, box_h, border_col)
Image

shaoziyang
Posts: 363
Joined: Sun Apr 17, 2016 1:55 pm

Re: Framebuffer wrap text

Post by shaoziyang » Sat Feb 24, 2018 3:14 am

It is great.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Framebuffer wrap text

Post by pythoncoder » Sat Feb 24, 2018 6:13 am

Neat :D An option to wrap in a way which respects word breaks and hyphens would be good.
Peter Hinch
Index to my micropython libraries.

Post Reply