Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS 

sys font alpha in as3

// apply a filter to a system font in order to adjust alpha

myTextField.filters = [new BlurFilter(0,0,0)];
myTextField.alpha = 0.5;

Center a text in Java Swing

Draws a string centered by calculating its position depending on the size.

String s;
int width, height;
Graphics g;

FontMetrics fm = getFontMetrics(ftDefault);
Rectangle2D textsize = fm.getStringBounds(s, g);
int xPos = (width - textsize.getWidth()) / 2;
int yPos = (height - textsize.getHeight()) / 2 + fm.getAscent();

g.drawString(s, xPos, yPos);

Actionscript _Text Class

Useful functions for adding dynamic text fields. Don't forget, you have to add the font of choice into the main movie Library for this to work (Library Panel Menu > New Font). The name you give the font is the string that you pass to the getTextFormat function for the "font" parameter. Setup your font styles with getTextFormat, setup your dynamic text box with getTextField, and then add text to the text box with appendTextField.

dynamic class _Text {
	static function getTextFormat(font:String,size:Number,color:Number,leading:Number,url:String,target:String){
		var fmt:TextFormat = new TextFormat();
		fmt.font = font;
		fmt.kerning = true;
		fmt.leading = (leading != undefined && leading != null) ? leading : 0;
		fmt.bold = false;
		fmt.size = (size != undefined && size != null) ? size : 11;
		fmt.color = (color != undefined && color != null) ? color : 0x000000;

		if (url != undefined && url != null) {
			fmt.url = url;
			fmt.target = (target != undefined && target != null) ? target : "_self";
		}
		return (fmt);
	}
	
	static function getTextField(targetMC,targetDepth,txtFieldName,x,y,w,h,txtObj){
		var targetDepth = (targetDepth != undefined && targetDepth != null) ? targetDepth : targetMC.getNextHighestDepth();
		var txtfld = targetMC.createTextField(txtFieldName, targetDepth, x, y, w, h);
		txtfld.antiAliasType = (txtObj.antiAliasType) ? txtObj.antiAliasType : "advanced";
		txtfld.sharpness = (txtObj.sharpness) ? txtObj.sharpness : -60;
		txtfld.thickness = (txtObj.thickness) ? txtObj.thickness : -100;
		txtfld.embedFonts = (txtObj.embedFonts) ? txtObj.embedFonts : true;
		txtfld.selectable = (txtObj.selectable) ? txtObj.selectable : false;
		txtfld.html = (txtObj.html) ? txtObj.html : true;
		txtfld.multiline = (txtObj.multiline) ? txtObj.multiline : true;
		txtfld.autoSize = (txtObj.autoSize) ? txtObj.autoSize : "left";
		
		if (txtObj.htmlText) txtfld.htmlText = txtObj.htmlText;
		if (txtObj.txtFormat) txtfld.setTextFormat(txtObj.txtFormat);
		
		if (txtObj.wordWrap == undefined || txtObj.wordWrap == null) txtfld._width = txtfld.textWidth + 10;
		else txtfld.wordWrap = txtObj.wordWrap;
		return txtfld;
	}
	
	static function appendTextField(txtfld,txtfrmt,txt){
		var beginIndex:Number = txtfld.htmlText.length;
		txtfld.setNewTextFormat(txtfrmt);
		txtfld.replaceText(beginIndex,beginIndex,txt);
	}
}

Linux - XTerm font size

// Aumenta la dimensione del carattere sul terminale

xterm -geometry 640x480 -fn *-fixed-*-*-*-20-*

Tag cloud using Text()


from appuifw import *
app.body = t = Text()

fonts = [u'', u'LatinPlain12', u'LatinBold12', u'LatinBold13', u'LatinBold17', u'LatinBold19']
tags = [(1, "apache"), (1, "array"), (1, "bash"), (1, "c"), (1, "cli"), (1, "csharp"), (1, "css"),
  (1, "database"), (1, "date"), (1, "expressionengine"), (1, "file"), (2, "html"), (1, "image"),
  (2, "java"), (4, "javascript"), (1, "lighttpd"), (1, "linux"), (1, "mac"), (1, "math"), (1, "mysql"),
  (1, "osx"), (1, "perl"), (3, "php"), (1, "pys60"), (5, "python"), (4, "rails"), (1, "regex"),
 (4, "ruby"), (1, "rubyonrails"), (1, "series"), (3, "series60"), (1, "servers"), (2, "shell"), (2, "sql"),
 (1, "ssh"), (1, "string"), (1, "text"), (1, "time"), (1, "unix"), (1, "web"), (1, "windows"), (1, "xml"),]

for level, tag in tags:
    t.font = fonts[level]
    t.add(tag + u' ')

See screenshot.

If using font is not enough, we can use other styles or colors.
See a related snippet.

Preview available fonts

>>> from appuifw import *
>>> fonts = available_fonts()
>>> fonts.sort()
>>> t = Text()
>>> for f in fonts:
...   t.font = f
...   t.add(f + ' ')
...
>>> app.body = t

See screenshot.

Using <font> (font tag) within pys60 Text widget

The Text widget allow rich text. However, it's quite
difficult to use. You need to set each attribute
(font, style, highlight, color) of the widget
before adding more text with differert style.

So, I make a function that make it a bit easier.
The font tag (<font></font>) is used (borrowed from HTML).
Attributes allowed are
- color ( #RRGGBB or 0xRRGGBB or color name)
- face ( both font and size eg. albi17b )
- style ( bold, italic, underline or strikethrough )
(styles can be combined using comma)
- highlight ( standard, rounded, shadow)
- hcolor ( highlight color )
from appuifw import *

def process_color(color):
    color_name = {
        'red': 0xff0000, 'green': 0x008000, 'blue':0x0000ff,       
        'black': 0,      'white':0xffffff,      'yellow': 0xffff00
        }
    if color.startswith('#'):   # HTML format #000000
        return int(color[1:], 16)
    if color.startswith('0x'):  # pys60 format 0x000000
        return int(color, 16)
    return color_name[color]

def set_ml(t, s):
    stack = []
    t.clear()
    t.font = 'normal'
    i = 0
    while i < len(s):
        if s.startswith('<', i):  # tag end or tag begin
            j = s.find('>', i) + 1
            if s[i:i+7] == '</font>' or s[i:i+3] == '</>':
                t.color, t.font, t.style, t.highlight_color = stack.pop()
            else:
                stack.append([t.color, t.font, t.style, t.highlight_color])
                to_style = 0
                for attr_val in s[i:j-1].split(' '):
                    if '=' in attr_val:
                        attr, val = attr_val.split('=')
                        if attr == 'color':
                            t.color = process_color(val)
                        elif attr == 'face':
                            t.font = unicode(val)
                        elif attr == 'hcolor':
                            t.highlight_color = process_color(val)
                        elif attr == 'style':   # style and highlight go together
                            to_style |= eval('|'.join(['STYLE_' + st.upper() for st in val.split(',')]))
                        elif attr == 'highlight':
                            to_style |= eval("HIGHLIGHT_" + val.upper())
                if to_style:
                    t.style = to_style
        else:    # normal text
            j = s.find('<', i)
            if j == -1: j = len(s)
            text = u'' + s[i:j].replace('&lt;', '<')
            t.add(text)
        i = j      # go next chunk


Now you can use it easily
>>> t = app.body   # use the default Text widget that start pys60
>>> set_ml(t, '<font color=red>Hello</font> <font style=bold>World</font>.')
>>>  # a stylish 'Hello World' is displayed

Notice:
- Quotation marks are not used to specify attribute values.
- A </> shorthand can be used for </font>
- <font> can be nested.

Readable, resizable font in stylesheet

body, td {font:90% Tahoma, [other fonts]}

Today I found an apps where its Thai font is ugly.
I added this 90% Tahoma to its font style.
Don't use pixel (px). It's unresizable (unless using FF).

Inputing non-ascii characters

My mobile phone (6600) doesn't have a Thai input method.
(You can buy a special software to do it)
After a lot of my thought experiments, I got an easy
example from my friend on this. You do a 2-level popup menu
to let people choose from the character table.
from appuifw import *

def thai_input():
    first_list = ['  '.join(thai_char[i:i+11]) for i in range(0,77,11)]
    y = popup_menu(first_list, u'select Thai char')
    if y is not None:
        x = popup_menu(thai_char[11*y:11*(y+1)], u'select Thai char')
        if x is not None:
            t.add(thai_char[11*y + x])

thai_char = [unichr(0x0e01+i) for i in range(77)]   # 77 thai characters

app.body = t = Text()
app.menu = [(u'thai', thai_input), (u'clear screen', t.clear)] 

# wait for user to exit program
import e32      
lock = e32.Ao_lock() 
app.exit_key_handler=lock.signal
lock.wait()


For other language, you can change the unicode offset (0x0e01)
and number of characters (77) to that of your language.
One requirement for this method is that the phone must be
able to display font in your language already.
(I have previously install Thai font on my 6600)
An alternative method to implement this will be manually drawing
your text (combile character from image font file).
I may do that some day.
« Newer Snippets
Older Snippets »
Showing 1-9 of 9 total  RSS