How to automatically set TextField()'s width - apache-flex

I'm trying to set the width of a Textfield() object based on it's string content that I have set-
Is there a way to dynamically set this once the string has been sent to the object?
I have:
var t1:TextField = new TextField()
t1.x = stage.stageWidth / 2;
t1.y = stage.stageHeight / 2;
t1.text = "some string that i would want to render";
t1.textColor = 0x000000;
t1.cacheAsBitmap = true;
addChild(t1);
Thanks for any suggestions...
jml

TextField.autoSize?
edit:
You should read the documentation correctly, it's a member variable that actually needs to be set. I'll give you a quick example on how this works:
var tf:TextField = new TextField();
tf.text = 'Some text.';
tf.autoSize = TextFieldAutoSize.LEFT;
tf.x = ( stage.stageWidth - tf.width ) / 2;
tf.y = ( stage.stageHeight - tf.height ) / 2;
Alternatively you can also align the text field first and use TextFieldAutoSize.CENTER to keep it aligned in the center.

t1.text = "Some text";
t1.width = t1.textWidth + 5;
t1.height = t1.textHeight + 5;
Why the + 5? Because Adobe sucks and adds an internal gutter around your stuff. Per the docs this is supposed to be 2px per side, but it's actually slightly more, so you add another +1 for good measure.

you could try using the getCharBoundaries() method (it returns a rectangle surrounding a character at a specified index). Use that to get the rectangle from the first and last chars and set the width to the difference of those rectangles.
Pretty convoluted, there's got to be a better way, but if not this should work.

Related

Unable to see 2D text sprites in Autodesk Forge

I'm trying to render 2D text using Sprites in the Autodesk Forge viewer, but I can't get it to show up. If I consult the layer by console I see that it contains the created Sprite but nevertheless I can’t see it in the scene. I have tried different scaling and position settings but no results.
I attach the code below:
function createText(text, preferencia, tamanyo) {
var sprite = spriteTexto("Prueba texto sprite", preferencia, tamanyo);
if (!NOP_VIEWER.impl.overlayScenes['overlaySprites'])
NOP_VIEWER.impl.createOverlayScene('overlaySprites');
NOP_VIEWER.impl.addOverlay('overlaySprites', sprite);
}
function spriteTexto(text, preferencia, tamanyo) {
var fontface = NOP_VIEWER.fontName;
var fontsize = 18; //tamanyo
var borderThickness = 4;
var borderColor = { r:0, g:0, b:0, a:1.0 };
var backgroundColor = { r:0, g:0, b:0, a:0.0 };
var textColor = { r:0, g:0, b:255, a:1 }; //hexadecimalARgb(preferencia.color);
var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = "Bold " + fontsize + "px " + fontface;
var metrics = context.measureText( text );
var textWidth = metrics.width;
context.fillStyle = "rgba(" + backgroundColor.r + "," + backgroundColor.g + "," + backgroundColor.b + "," + backgroundColor.a + ")";
context.strokeStyle = "rgba(" + borderColor.r + "," + borderColor.g + "," + borderColor.b + "," + borderColor.a + ")";
context.fillStyle = "rgba(" + textColor.r+", " + textColor.g + ", " + textColor.b + ", 1.0)";
context.fillText( text, borderThickness, fontsize + borderThickness);
var texture = new THREE.Texture(canvas);
texture.needsUpdate = true;
var spriteMaterial = new THREE.SpriteMaterial( { map: texture, useScreenCoordinates: false } );
var sprite = new THREE.Sprite( spriteMaterial );
sprite.scale.set(1*fontsize,1*fontsize,1*fontsize);
sprite.position.set(5,5,6);
return sprite;
}
I would be very grateful if you could help me find the error, thank you very much in advance for your help!
EDIT:------------------------------------------------
We want to render 2D text that can be interacted with (specifically select, rotate, and move).
To do this currently we are working with meshes (using MeshBasicMaterial, Mesh and TextGeometry), but it turns out that the text does not look perfectly sharp, it presents aliasing and we’ve found that according to the API reference, the antialiasing is not applicable to 2d.
Here are some examples of the problem, as you can see, the more we move away from the plane, the worse the text looks (and even up close it doesn't look perfect):
We were trying to make a test representing the text with Sprites (despite the fact that it would mean having to change the entire implementation already made with meshes) to try to implement it in another way that will solve the problem. But we see that it is not possible either.
How can we correct the rendering of the text then? Is there a way to fix it or is this the most we can get in 2D? We've tried searching for information on this but we haven't find anything helpful.
Unfortunately, Forge Viewer doesn't support THREE.Sprite at present. It uses a self-maintained three.js r71 and removes this support as I know.
Could you share the use case in detail on why you want to use THREE.Sprite with Forge Viewer? If you don't want to share that publicly, you can send it to forge (DOT) help (AT) autodesk (DOT) com.

How do you break a line of text within InDesign scripts?

So I'm new to InDesign CC scripting, but I really just need a very simple solution, or at least I hope that it's a simple solution. I have a script for adding a watermark to a document for export, however i'd like it to be on two lines and take up more space on the page rather than just one line. Below is the script I'm using:
var myDoc = app.activeDocument,
myPdfExportPreset = "[High Quality Print]",
myPdfFile = File(myDoc.fullName.fsName.replace(/.indd$/i, "") + ".pdf");
app.scriptPreferences.measurementUnit = MeasurementUnits.INCHES
var docHeight = myDoc.documentPreferences.pageHeight
var docWidth = myDoc.documentPreferences.pageWidth
with(myDoc.watermarkPreferences)
{
watermarkVisibility = true;
watermarkDoPrint = true;
watermarkDrawInBack = false;
watermarkText = "I would like the code to split between the word split and between";
watermarkFontFamily = "Helvetica";
watermarkFontStyle = "Bold";
watermarkFontPointSize = Math.round(docWidth * 7);
watermarkFontColor = [0, 0, 0];
watermarkOpacity = 15;
watermarkRotation = -25;
watermarkHorizontalPosition = WatermarkHorizontalPositionEnum.watermarkHCenter;
watermarkHorizontalOffset = 0;
watermarkVerticalPosition = WatermarkVerticalPositionEnum.watermarkVCenter;
watermarkVerticalOffset = 0;
}
If anyone has an idea on how to insert a line break, I'm not sure if it's like html where you can just <br> and be done with it, but that's kind of what I'm looking for, if that makes sense. Thanks so much in advance!

how get width and height of Image control

I want to change the size of my image in asp.net proportionally, the problem is that I can't get the actual size of the image which is loaded from database. here is the code:
imgAvatar.ImageUrl = "~/Modules/FileViewer.ashx?id=" + o.EventID;
double r = imgAvatar.Width.Value / 300.00;
imgAvatar.Width = new Unit(300, UnitType.Pixel);
imgAvatar.Height = new Unit(imgAvatar.Height.Value / r, UnitType.Pixel);
but the imgAvatar.Width.Value is always 0.0.
what would you suggest to me?
Do not set width and height. The rendered IMG tag will be sized to the size of downloaded image.
However, if the image is too large you might have a problem. In that case, use CSS to set max:
max-width: 300px;
max-height: 300px;
I might have misunderstand the question, considering my answer above. Anyways, the way I see that done would be similar to this:
System.Drawing.Image image = System.Drawing.Image.FromFile(this.Server.MapUrl("~/image path here"));
// sorry if the above line doesn't compile; writing from memory, use intellisense to find these classes/methods
// image.Width and image.Height will work here
Takes the size of the image with Bitmap and calls the below function to resize
Bitmap myBitmap;
string fileName = "foreverAlone.jpg";
myBitmap = new Bitmap(fileName);
Size newSize = NewImageSize(myBitmap.Height, myBitmap.Width, 100);//myBitMap.Height and myBitMap.Width is how you take the original size
Check BitMap class here Bitmap Class - MSDN Article
This code returns new size of the image, and image quality remains the same -no reduce-, FormatSize parameter decides the new size.
public Size NewImageSize(int OriginalHeight, int OriginalWidth, double FormatSize)
{
Size NewSize;
double tempval;
if (OriginalHeight > FormatSize && OriginalWidth > FormatSize)
{
if (OriginalHeight > OriginalWidth)
tempval = FormatSize / Convert.ToDouble(OriginalHeight);
else
tempval = FormatSize / Convert.ToDouble(OriginalWidth);
NewSize = new Size(Convert.ToInt32(tempval * OriginalWidth), Convert.ToInt32(tempval * OriginalHeight));
}
else
NewSize = new Size(OriginalWidth, OriginalHeight);
return NewSize;
}

How do you get the line height of the text in a Spark Label?

How do you determine the line height (in pixels) of the text in a Spark Label?
keyle's answer will only give you the height of the text, not the actual 'lineHeight' style. You can easily get that style like this:
myLabel.getStyle("lineHeight");
The problem is that this can return a relative value (a percentage) or an absolute value (in pixels). The default - if no lineHeight was explicitely set - is "120%".
So here's how we can get the value in pixels in both cases:
var lineHeightStyle:* = myLabel.getStyle("lineHeight");
//its already a value in pixels
if (lineHeightStyle is Number) var lineHeight:Number = lineHeightStyle;
//it's a relative value: let's calculate
else {
var lineMetrics:TextLineMetrics = myLabel.measureText(myLabel.text);
//get the numeric value from the string and divide it by 100
var ratio:Number = int(lineHeightStyle.match(/\d+/)[0]) / 100;
lineHeight = lineMetrics.height * ratio;
}
Have you tried the following?
var lineMetrics:TextLineMetrics = label.measureText(label.text);
var result:Number = lineMetrics.height;

How do I get a bounding box for the current selection?

I'd like to do fancy things the selection indicator. How do I get the bounding box for the currently selected characters?
This was non-trivial. First, a selection may require more than one rectangle. Next, there's no convenient way to do it.
Here's what I had to do:
var start:int = op.activePosition < op.anchorPosition ? op.activePosition : op.anchorPosition;
var end:int = op.activePosition > op.anchorPosition ? op.activePosition : op.anchorPosition;
var textFlow:TextFlow = this.textFlow;
var rectangles:Dictionary = new Dictionary();
// For each selected character, make a box
for( var i:int=start; i < end; i++) {
var flowLine:TextFlowLine = textFlow.flowComposer.findLineAtPosition( i, true );
if( rectangles[ flowLine.absoluteStart ] == null ) {
rectangles[ flowLine.absoluteStart ] = new Rectangle();
(rectangles[ flowLine.absoluteStart ] as Rectangle).x = 0xffffff;
(rectangles[ flowLine.absoluteStart ] as Rectangle).right = 0;
}
var currentRect:Rectangle = rectangles[ flowLine.absoluteStart ];
var textLine:TextLine = flowLine.getTextLine(true);
var atomIndex:int = textLine.getAtomIndexAtCharIndex( i );
if( atomIndex >= 0) {
var atomBounds:Rectangle = textLine.getAtomBounds( atomIndex );
var pt:Point = this.globalToLocal( textLine.localToGlobal( new Point( atomBounds.left, atomBounds.top ) ) );
if( pt.x <= currentRect.left ) {
currentRect.left = pt.x;
currentRect.top = pt.y;
}
pt = this.globalToLocal( textLine.localToGlobal( new Point( atomBounds.right, atomBounds.bottom) ) );
if( pt.x >= currentRect.right ) {
currentRect.right = pt.x;
currentRect.bottom = pt.y;
}
}
}
return rectangles;
I don't believe there's a trivial way to get total control over this, from looking around at the docs a bit I saw this:
http://opensource.adobe.com/wiki/display/flexsdk/Spark+Text+Primitives#SparkTextPrimitives-FTE
[Style(name="focusedTextSelectionColor", type="uint", format="Color", inherit="yes")]
[Style(name="inactiveTextSelectionColor", type="uint", format="Color", inherit="yes")]
[Style(name="unfocusedTextSelectionColor", type="uint", format="Color", inherit="yes")]
also to note:
anchor position - A character index specifying the end of the selection that stays fixed when you extend the selection with the arrow keys.
active position - A character index specifying the end of the selection that moves when you extend the selection with the arrow keys.
Since these are all only colors (or indices) I don't know if they'll get at all the fanciness you'd like to do. I'd worked on something in Flex 3 to deal with custom text selection controls and ended up using an "off screen buffer" of sorts where I put a TextField offscreen with the same properties as the one on screen then dump the characters 1 by 1 until I got to the desired width then I could figure out where in the characters the control was dropped(kind of like android selection).
I would suggest searching for the above styles in the SDK you have (particularly in RichEditableText and its super classes, I would do this but there's quite a few versions out there now and don't know which one your using, TLF and FTE are both a bit in flux it seems). Once you find where these styles are used you'll probably be in the vicinity of the selection indicator drawing code and will likely need to extend from whatever class that is in order to override the appropriate methods.
Sorry I can't give you a straight answer but hopefully this helps or someone else is able to chime in if there's an easier way.
Shaun

Resources