Color a button in Scriptui and text positioning.
I found Scriptui code to change the color of a button but there is one part that is not working correctly. To place the text on the button, the text width is computed by graphics.measureString routine. Then the (button width - that value) / 2 should give the coordinate where the upper left corner of the text will be placed. I find that the 2 (I call it factor) in the divisor is not correct always. Position error of 1 or 2 pixel would be OK but it is way off. Italic and Bold need to be taken into account also.
Anyone have a solution that is good within a pixel or two?
The code below is first my version of older code referred to by web links.
I appreciate any help.
RONC
my code *******************************
// color button scriptui
// http://forums.adobe.com/message/2327073
// https://gist.github.com/milligramme/1353791#file-color_scriptui_button-js-L2
var u;
var dlg = new Window('dialog', 'Test');
var btn1 = dlg.add('button', u, 'OK', { name: 'ok' });
var btn2 = dlg.add('iconbutton', u, u, { name: 'gray', style: 'toolbutton' });
var factor = 2;
btn2.size = [120, 30];
btn2.text = "Test1";
btn2Graphics = btn2.graphics;
btn2.fillBrush = btn2Graphics.newBrush(btn2Graphics.BrushType.SOLID_COLOR, [0.5, 0.5, 0.5, 1.0]);
btn2Graphics.font = ScriptUI.newFont("ARIAL", ScriptUI.FontStyle.BOLD, 20);
btn2.textPen = btn2Graphics.newPen(btn2Graphics.PenType.SOLID_COLOR, [1.0, 1.0, 1.0, 1], 1);
btn2.onDraw = function ()
{
with (this)
{
graphics.drawOSControl();
// controlObj.graphics.rectPath (left, top[, width, height])
graphics.rectPath(0, 0, size[0], size[1]);
graphics.fillPath(fillBrush);
if (text)
{
// controlObj.graphics.measureString (text, font[, boundingWidth])
var x = (size[0] - graphics.measureString(text, graphics.font, size[0])[0]) / factor;
var y = 3;
// controlObj.graphics.drawString (text, pen, x, y, font)
graphics.drawString(text, textPen, x, y, graphics.font);
}
}
};
dlg.show();
Original code ***********************************
/*
var u;
var dlg = new Window('dialog', 'Test');
var pnl = dlg.add('panel', u, 'My Panel');
var btn = pnl.add('button', u, 'My Button', {name:'ok'});
var btn2 = pnl.add('iconbutton', u, u, {name:'orange', style: 'toolbutton'});
btn2.size = [200,20];
btn2.fillBrush = btn2.graphics.newBrush( btn2.graphics.BrushType.SOLID_COLOR, [1, 0.7, 0, 0.5] );
btn2.text = "Hello, Harbs";
btn2.textPen = btn2.graphics.newPen (btn2.graphics.PenType.SOLID_COLOR,[0,0.5,0,1], 1);
btn2.onDraw = function(){
with( this ) {
graphics.drawOSControl();
graphics.rectPath(0,0,size[0],size[1]);
graphics.fillPath(fillBrush);
if( text ) graphics.drawString(text,textPen,(size[0]-graphics.measureString (text,graphics.font,size[0])[0])/2,3,graphics.font);
}
};
dlg.show();
*/

