Two colors in one text field using Actionscript 2 - actionscript-2

I'm trying to get realtime rainbow text in a single word and reset to red when I space to the next word to create another rainbow word.
For instance, if I want to type the string, "his forgiveness", I want "h" to be red, "i" to be orange, "s" to be yellow, "f" to be red, "o" to be orange, "r" to be yellow, "g" to be green, "i" to be blue, "v" to be indigo, "e" to be violet. The remaining, "ness" can all be violet, I don't care. I just need the original concept down.
So far, I'm only able to change the color of the whole text area on a keypress(s) and not a single string character.
To fast forward to where I am, follow this quick 4 point process:
(1/4)Paste the following code on the stage.
counter = -1;
var key:Object = {onKeyDown:function () {
counter = counter+1;
if (counter == 1) {
inp.textColor = 0xFF0000;
}
if (counter == 2) {
inp.textColor = 0xFF9900;
}
if (counter == 3) {
inp.textColor = 0xFFFF00;
}
}};
Key.addListener(key);
(2/4)Make an input box with the instance name, "inp"
(3/4)Test the movie.
(4/4)Select the textbox and start typing in it.
I only have it changing the whole text box from your default color to red then orange than yellow. Getting a true rainbow code will be what I've long waited for if you can help.

In order to implement different colors on a single textfield you must use this properties on your textfield:
myTextField.html = true
myTextField.htmlText = 'bli bli bli<font color="#0000FF">bla bla bla/font>'
or you can use the TextFormat class to do so.
Here is how you can do.
tField.text = "bli bli bli";
var tFormat:TextFormat = new TextFormat();
tFormat.color = 0xff0000;
tField.setTextFormat(0,5,tFormat);
tFormat.color = 0x33cc33;
tField.setTextFormat(5,9,tFormat);
and in order to get the colors as you type use this class:
package {
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
import flash.events.KeyboardEvent;
import flash.events.Event;
public class ColorTextField extends TextField{
var tf:TextFormat = new TextFormat();
var ar:Array = new Array(0xFF0000,0x00FF00,0x0000FF,0x123456);
public function ColorTextField() {
// constructor code
this.type = TextFieldType.INPUT;
tf.size = 33;
this.defaultTextFormat = tf;
this.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
}
private function onKeyUp(event:KeyboardEvent):void{
var index:int = 0;
var colorIndex:int = 0;
while (index < this.text.length){
var char:String = this.text.substr(index,1);
if(char == " "){
colorIndex = 0;
}else{
tf.color = ar[colorIndex];
trace(index + "-" +ar[colorIndex]);
this.setTextFormat(tf,index,index+1);
colorIndex++;
if(colorIndex > ar.length-1){
colorIndex = ar.length-1;
}
}
index++;
}
}
}
}
this how you implement it.Create a new AS3 Fla and assign this as base class:
package {
import flash.display.MovieClip;
import flash.text.TextField;
import flash.text.TextFieldType;
public class MyClass extends MovieClip {
var tf:ColorTextField = new ColorTextField();
public function MyClass() {
// constructor code
tf.width = 500;
tf.text = "12345";
this.addChild(tf);
}
}
}
does not matter where you input the new text

Related

my code is only drawing a straight line no matter how many sides i input in the pSides JTextFields

When I input a digit in the JTextfields it should pass through my actionListener to store all the values (ID, number of sides, length of sides and color) into an arraylist. It should then be used in my polygonContainer class that goes through a for loop and a polygon formula, then prints it out. However what comes out all the time is a straight line.
This is the code i tried:
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
public class ContainerFrame extends JFrame{
ArrayList<PolygonContainer> polygons = new ArrayList<>();
// JTextFields for the number of sides, side length, color, and ID
public JTextField pSides, pSidesLengths, pColor, pID;
// Button for submission
public JButton submitButton;
public void createComponents() {
// Initialize the JTextFields
pSides = new JTextField();
pSidesLengths = new JTextField();
pColor = new JTextField();
pID = new JTextField();
submitButton = new JButton("Submit");
submitButton.addActionListener(new ContainerButtonHandler(this));
JPanel textFieldsPanel = new JPanel();
// uses a gridlayout to organise the textfields then sets it as north
textFieldsPanel.setLayout(new GridLayout(5, 2));
textFieldsPanel.add(new JLabel("Sides:"));
textFieldsPanel.add(pSides);
textFieldsPanel.add(new JLabel("Sides Length:"));
textFieldsPanel.add(pSidesLengths);
textFieldsPanel.add(new JLabel("Color:"));
textFieldsPanel.add(pColor);
textFieldsPanel.add(new JLabel("ID:"));
textFieldsPanel.add(pID);
add(textFieldsPanel, BorderLayout.NORTH);
add(submitButton, BorderLayout.SOUTH);
JPanel drawPanel = new ContainerPanel(this);
add(drawPanel, BorderLayout.CENTER);
setSize(1600, 900);
setVisible(true);
setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); // Close action.
}
public static void main(String[] args) {
ContainerFrame cFrame = new ContainerFrame();
cFrame.createComponents();
}
}
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
class ContainerButtonHandler implements ActionListener {
ContainerFrame theApp; // Reference to ContainerFrame object
// ButtonHandler constructor
ContainerButtonHandler(ContainerFrame app) {
theApp = app;
}
public void actionPerformed(ActionEvent e) {
// Get the text from the JTextFields using the getText method
String sides = theApp.pSides.getText();
String sidesLengths = theApp.pSidesLengths.getText();
String id = theApp.pID.getText();
//parse the values as integers
int intSides = Integer.parseInt(sides);
int intSidesLength = Integer.parseInt(sidesLengths);
int intId = Integer.parseInt(id);
//does the input validation where sides, sides length and id needs to be positive integers
if (intId >= 100000 && intId <= 999999 && intSides >= 0 && intSidesLength >= 0) {
// The inputs are valid
String color = theApp.pColor.getText();
// Store the values in an arraylist or other data structure
ArrayList<String> polygonArray = new ArrayList<String>();
polygonArray.add(sides);
polygonArray.add(sidesLengths);
polygonArray.add(color);
polygonArray.add(id);
PolygonContainer polygon = new PolygonContainer(polygonArray);
theApp.polygons.add(polygon);
theApp.repaint();
JOptionPane.showMessageDialog(theApp, "Polygon" + id + "was added to the list.", "Success", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(theApp, "The Polygon" + id + "was not added to the list as a valid Id was not provided.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
}
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
public class PolygonContainer implements Comparable<PolygonContainer>{
Color pColor = Color.BLACK; // Colour of the polygon, set to a Colour object, default set to black
int pId = 000000; // Polygon ID should be a six digit non-negative integer
int pSides; // Number of sides of the polygon, should be non-negative value
int pSideLengths; // Length of each side in pixels of the polygon, should be non-negative value
int polyCenX; // x value of centre point (pixel) of polygon when drawn on the panel
int polyCenY; // y value of centre point (pixel of polygon when drawn on the panel
int [] pointsX; // int array containing x values of each vertex (corner point) of the polygon
int [] pointsY; // int array containing y values of each vertex (corner point) of the polygon
// Constructor currently set the number of sides and the equal length of each side of the Polygon
//Constructor that takes the values from the array
public PolygonContainer(ArrayList<String> values){
this.pSides = Integer.parseInt(values.get(0));
this.pSideLengths = Integer.parseInt(values.get(1));
this.pColor = Color.getColor(values.get(2));
this.pId = Integer.parseInt(values.get(3));
pointsX = new int[pSides];
pointsY = new int[pSides];
}
// Used to populate the points array with the vertices corners (points) and construct a polygon with the
// number of sides defined by pSides and the length of each side defined by pSideLength.
// Dimension object that is passed in as an argument is used to get the width and height of the ContainerPanel
// and used to determine the x and y values of its centre point that will be used to position the drawn Polygon.
public Polygon getPolygonPoints(Dimension dim) {
polyCenX = dim.width / 2; // x value of centre point of the polygon
polyCenY = dim.height / 2; // y value of centre point of the polygon
Polygon p = new Polygon();
for (int i = 0; i < pSides; i++) {
// Calculate the x and y coordinates of the ith point of the polygon
int x = polyCenX + pSideLengths * (int) Math.cos(2.0 * Math.PI * i / pSides);
int y = polyCenY + pSideLengths * (int) Math.sin(2.0 * Math.PI * i / pSides);
// Add the x and y coordinates to the pointsX and pointsY arrays
pointsX[i] = x;
pointsY[i] = y;
// Add the point to the polygon object using the addPoint method
p.addPoint(x, y);
}
return p;
}
// You will need to modify this method to set the colour of the Polygon to be drawn
// Remember that Graphics2D has a setColor() method available for this purpose
public void drawPolygon(Graphics2D g, Dimension d) {
//Set color of polygon
g.setColor(pColor);
Polygon p = getPolygonPoints(d);
g.draw(p);
//this creates a bounding box around the polygon
Rectangle2D bounds = p.getBounds2D();
g.draw(bounds);
}
// gets a stored ID
public int getID() {
return pId;
}
#Override
// method used for comparing PolygonContainer objects based on stored ids, you need to complete the method
public int compareTo(PolygonContainer o) {
return 0;
}
// outputs a string representation of the PolygonContainer object, you need to complete this to use for testing
public String toString()
{
return "";
}
}
import javax.swing.JPanel;
import java.awt.*;
public class ContainerPanel extends JPanel{
ContainerFrame conFrame;
public ContainerPanel(ContainerFrame cf) {
conFrame = cf; // reference to ContainerFrame object
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D comp = (Graphics2D)g; // You will need to use a Graphics2D objects for this
Dimension size = getSize(); // You will need to use this Dimension object to get
// the width / height of the JPanel in which the
// Polygon is going to be drawn
for (PolygonContainer polygon : conFrame.polygons) {
polygon.drawPolygon(comp, size);
}
}
}
JFrame

How to change color of a part of text from < to > [duplicate]

I'm trying to color parts of a string to be appended to a RichTextBox. I have a string built from different strings.
string temp = "[" + DateTime.Now.ToShortTimeString() + "] " +
userid + " " + message + Environment.NewLine;
This is what the message would look like once it is constructed.
[9:23pm] User: my message here.
I want everything within and including the brackets [9:23] to be one color, 'user' to be another color and the message to be another color. Then I'd like the string appended to my RichTextBox.
How can I accomplish this?
Here is an extension method that overloads the AppendText method with a color parameter:
public static class RichTextBoxExtensions
{
public static void AppendText(this RichTextBox box, string text, Color color)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
}
And this is how you would use it:
var userid = "USER0001";
var message = "Access denied";
var box = new RichTextBox
{
Dock = DockStyle.Fill,
Font = new Font("Courier New", 10)
};
box.AppendText("[" + DateTime.Now.ToShortTimeString() + "]", Color.Red);
box.AppendText(" ");
box.AppendText(userid, Color.Green);
box.AppendText(": ");
box.AppendText(message, Color.Blue);
box.AppendText(Environment.NewLine);
new Form {Controls = {box}}.ShowDialog();
Note that you may notice some flickering if you're outputting a lot of messages. See this C# Corner article for ideas on how to reduce RichTextBox flicker.
I have expanded the method with font as a parameter:
public static void AppendText(this RichTextBox box, string text, Color color, Font font)
{
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = color;
box.SelectionFont = font;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
}
This is the modified version that I put in my code (I'm using .Net 4.5) but I think it should work on 4.0 too.
public void AppendText(string text, Color color, bool addNewLine = false)
{
box.SuspendLayout();
box.SelectionColor = color;
box.AppendText(addNewLine
? $"{text}{Environment.NewLine}"
: text);
box.ScrollToCaret();
box.ResumeLayout();
}
Differences with original one:
Possibility to add text to a new line or simply append it
No need to change selection, it works the same
Inserted ScrollToCaret to force autoscroll
Added SuspendLayout/ResumeLayout calls for better performance
EDIT : sorry this is a WPF answer
I think modifying a "selected text" in a RichTextBox isn't the right way to add colored text.
So here a method to add a "color block" :
Run run = new Run("This is my text");
run.Foreground = new SolidColorBrush(Colors.Red); // My Color
Paragraph paragraph = new Paragraph(run);
MyRichTextBlock.Document.Blocks.Add(paragraph);
From MSDN :
The Blocks property is the content property of RichTextBox. It is a
collection of Paragraph elements. Content in each Paragraph element
can contain the following elements:
Inline
InlineUIContainer
Run
Span
Bold
Hyperlink
Italic
Underline
LineBreak
So I think you have to split your string depending on parts color, and create as many Run objects as needed.
It`s work for me! I hope it will be useful to you!
public static RichTextBox RichTextBoxChangeWordColor(ref RichTextBox rtb, string startWord, string endWord, Color color)
{
rtb.SuspendLayout();
Point scroll = rtb.AutoScrollOffset;
int slct = rtb.SelectionIndent;
int ss = rtb.SelectionStart;
List<Point> ls = GetAllWordsIndecesBetween(rtb.Text, startWord, endWord, true);
foreach (var item in ls)
{
rtb.SelectionStart = item.X;
rtb.SelectionLength = item.Y - item.X;
rtb.SelectionColor = color;
}
rtb.SelectionStart = ss;
rtb.SelectionIndent = slct;
rtb.AutoScrollOffset = scroll;
rtb.ResumeLayout(true);
return rtb;
}
public static List<Point> GetAllWordsIndecesBetween(string intoText, string fromThis, string toThis,bool withSigns = true)
{
List<Point> result = new List<Point>();
Stack<int> stack = new Stack<int>();
bool start = false;
for (int i = 0; i < intoText.Length; i++)
{
string ssubstr = intoText.Substring(i);
if (ssubstr.StartsWith(fromThis) && ((fromThis == toThis && !start) || !ssubstr.StartsWith(toThis)))
{
if (!withSigns) i += fromThis.Length;
start = true;
stack.Push(i);
}
else if (ssubstr.StartsWith(toThis) )
{
if (withSigns) i += toThis.Length;
start = false;
if (stack.Count > 0)
{
int startindex = stack.Pop();
result.Add(new Point(startindex,i));
}
}
}
return result;
}
Selecting text as said from somebody, may the selection appear momentarily.
In Windows Forms applications there is no other solutions for the problem, but today I found a bad, working, way to solve: you can put a PictureBox in overlapping to the RichtextBox with the screenshot of if, during the selection and the changing color or font, making it after reappear all, when the operation is complete.
Code is here...
//The PictureBox has to be invisible before this, at creation
//tb variable is your RichTextBox
//inputPreview variable is your PictureBox
using (Graphics g = inputPreview.CreateGraphics())
{
Point loc = tb.PointToScreen(new Point(0, 0));
g.CopyFromScreen(loc, loc, tb.Size);
Point pt = tb.GetPositionFromCharIndex(tb.TextLength);
g.FillRectangle(new SolidBrush(Color.Red), new Rectangle(pt.X, 0, 100, tb.Height));
}
inputPreview.Invalidate();
inputPreview.Show();
//Your code here (example: tb.Select(...); tb.SelectionColor = ...;)
inputPreview.Hide();
Better is to use WPF; this solution isn't perfect, but for Winform it works.
I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.
static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
{
int pos = box.SelectionStart;
string s = box.Text;
for (int ix = 0; ; )
{
int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
if (jx < 0) break;
int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
box.SelectionStart = jx;
box.SelectionLength = ex - jx + 1;
box.SelectionColor = color1;
int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
if (bx == bxtest)
{
box.SelectionStart = ex + 1;
box.SelectionLength = bx - ex + 1;
box.SelectionColor = color2;
}
ix = ex + 1;
}
box.SelectionStart = pos;
box.SelectionLength = 0;
}
and this is how you call it
HighlightPhrase(richTextBox1, "<", ">","</", Color.Red, Color.Black);
private void Log(string s , Color? c = null)
{
richTextBox.SelectionStart = richTextBox.TextLength;
richTextBox.SelectionLength = 0;
richTextBox.SelectionColor = c ?? Color.Black;
richTextBox.AppendText((richTextBox.Lines.Count() == 0 ? "" : Environment.NewLine) + DateTime.Now + "\t" + s);
richTextBox.SelectionColor = Color.Black;
}
Using Selection in WPF, aggregating from several other answers, no other code is required (except Severity enum and GetSeverityColor function)
public void Log(string msg, Severity severity = Severity.Info)
{
string ts = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
string msg2 = ts + msg + "\n";
richTextBox.AppendText(msg2);
if (severity > Severity.Info)
{
int nlcount = msg2.ToCharArray().Count(a => a == '\n');
int len = msg2.Length + 3 * (nlcount)+2; //newlines are longer, this formula works fine
TextPointer myTextPointer1 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-len);
TextPointer myTextPointer2 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-1);
richTextBox.Selection.Select(myTextPointer1,myTextPointer2);
SolidColorBrush scb = new SolidColorBrush(GetSeverityColor(severity));
richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, scb);
}
richTextBox.ScrollToEnd();
}
I prepared a little helper for the RichTextBox control which makes it very easy to generate colored text on the screen:
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace Common.Helpers
{
public class ColouredText
{
public string Text;
public Color Foreground;
public Color Background;
public ColouredText(string text, Color foreground, Color background)
{
Text = text;
Foreground = foreground;
Background = background;
}
public ColouredText(string text, Color foreground) : this(text, foreground, Color.Transparent) { }
public ColouredText(string text) : this(text, Color.Transparent, Color.Transparent) { }
}
public static class RichTextBoxHelper
{
private static RichTextBox _AppendText(RichTextBox box, string text, Color foreColor, Color backColor)
{
if (string.IsNullOrEmpty(text)) return box;
box.SelectionStart = box.TextLength;
box.SelectionLength = 0;
box.SelectionColor = foreColor;
box.SelectionBackColor = backColor;
box.AppendText(text);
box.SelectionColor = box.ForeColor;
return box;
}
private static void _UpdateText(RichTextBox box, IEnumerable<ColouredText> newTextWithColors)
{
box.Text = "";
foreach (var text in newTextWithColors)
{
var foreColor = text.Foreground; if (foreColor == Color.Transparent) foreColor = box.ForeColor;
var backColor = text.Background; if (backColor == Color.Transparent) backColor = box.BackColor;
_AppendText(box, text.Text, foreColor, backColor);
}
}
public static void UpdateText(this RichTextBox richTextbox, IEnumerable<ColouredText> text)
{
if (richTextbox.InvokeRequired) richTextbox.Invoke((MethodInvoker)(() => { _UpdateText(richTextbox, text); }));
else _UpdateText(richTextbox, text);
}
public static void UpdateText(this RichTextBox richTextbox, ColouredText text)
{
var list = new List<ColouredText>() { text };
if (richTextbox.InvokeRequired) richTextbox.Invoke((MethodInvoker)(() => { _UpdateText(richTextbox, list); }));
else _UpdateText(richTextbox, list);
}
}
}
and now you can use:
var text = new List<ColouredText>()
{
new ColouredText($"text#1 ", Color.Black),
new ColouredText($"text#2 ", Color.Red, Color.Yellow),
new ColouredText($" "),
new ColouredText($"text#2 ", Color.White, Color.Black)
};
richTextBox1.UpdateText(text);
or simpler usage for single-line text:
richTextBox1.UpdateText(new ColouredText($"warning message", Color.Yellow, Color.Red));

How to force Mobile Vision for Android to read full lines of text

I have implemented Google's Mobile Vision for Android by following a tutorial. I am trying to build an app that will scan a receipt and find the numeric total. However, as I scan different receipts that are printed in different formats, the API will detect TextBlocks in what seems to be an arbitrary way. For example, in one receipt, if several words of text are separated by single spaces, then they are grouped into a single TextBlock. However, if two words of text are separated by lots of spaces, then they are separated as independent TextBlocks, even though they appear on the same "line". What I am trying to do is force the API to recognize each entire line of the receipt as a single entity. Is this possible?
public ArrayList<T> getAllGraphicsInRow(float rawY) {
synchronized (mLock) {
ArrayList<T> row = new ArrayList<>();
// Get the position of this View so the raw location can be offset relative to the view.
int[] location = new int[2];
this.getLocationOnScreen(location);
for (T graphic : mGraphics) {
float rawX = this.getWidth();
for (int i=0; i<rawX; i+=10){
if (graphic.contains(i - location[0], rawY - location[1])) {
if(!row.contains(graphic)) {
row.add(graphic);
}
}
}
}
return row;
}
}
This should be in the GraphicOverlay.java file and essentially fetches all the graphics in that row.
public static boolean almostEqual(double a, double b, double eps){
return Math.abs(a-b)<(eps);
}
public static boolean pointAlmostEqual(Point a, Point b){
return almostEqual(a.y,b.y,10);
}
public static boolean cornerPointAlmostEqual(Point[] rect1, Point[] rect2){
boolean almostEqual=true;
for (int i=0; i<rect1.length;i++){
if (!pointAlmostEqual(rect1[i],rect2[i])){
almostEqual=false;
}
}
return almostEqual;
}
private boolean onTap(float rawX, float rawY) {
String priceRegex = "(\\d+[,.]\\d\\d)";
ArrayList<OcrGraphic> graphics = mGraphicOverlay.getAllGraphicsInRow(rawY);
OcrGraphic currentGraphics = mGraphicOverlay.getGraphicAtLocation(rawX,rawY);
if (graphics !=null && currentGraphics!=null) {
List<? extends Text> currentComponents = currentGraphics.getTextBlock().getComponents();
final Pattern pattern = Pattern.compile(priceRegex);
final Pattern pattern1 = Pattern.compile(priceRegex);
TextBlock text = null;
Log.i("text results", "This many in the row: " + Integer.toString(graphics.size()));
ArrayList<Text> combinedComponents = new ArrayList<>();
for (OcrGraphic graphic : graphics) {
if (!graphic.equals(currentGraphics)) {
text = graphic.getTextBlock();
Log.i("text results", text.getValue());
combinedComponents.addAll(text.getComponents());
}
}
for (Text currentText : currentComponents) { // goes through components in the row
final Matcher matcher = pattern.matcher(currentText.getValue()); // looks for
Point[] currentPoint = currentText.getCornerPoints();
for (Text otherCurrentText : combinedComponents) {//Looks for other components that are in the same row
final Matcher otherMatcher = pattern1.matcher(otherCurrentText.getValue()); // looks for
Point[] innerCurrentPoint = otherCurrentText.getCornerPoints();
if (cornerPointAlmostEqual(currentPoint, innerCurrentPoint)) {
if (matcher.find()) { // if you click on the price
Log.i("oh yes", "Item: " + otherCurrentText.getValue());
Log.i("oh yes", "Value: " + matcher.group(1));
itemList.add(otherCurrentText.getValue());
priceList.add(Float.valueOf(matcher.group(1)));
}
if (otherMatcher.find()) { // if you click on the item
Log.i("oh yes", "Item: " + currentText.getValue());
Log.i("oh yes", "Value: " + otherMatcher.group(1));
itemList.add(currentText.getValue());
priceList.add(Float.valueOf(otherMatcher.group(1)));
}
Toast toast = Toast.makeText(this, " Text Captured!" , Toast.LENGTH_SHORT);
toast.show();
}
}
}
return true;
}
return false;
}
This should be in OcrCaptureActivity.java and it breaks up the TextBlock into lines and finds the blocks in the same row as the line and checks if the components are all prices, and prints all value accordingly.
The eps value in almostEqual is the tolerance for how tall it checks for graphics in the row.

Displaying a fading balloon type message box

I need to have a balloon like message box that displays for a few seconds and then fades away (not disappears at once)
Please advise how to do this.
Thanks
Furqan
Try this:
Dim buttonToolTip As New ToolTip()
with buttonToolTip
.ToolTipTitle = "Button Tooltip"
.UseFading = True
.UseAnimation = True
.IsBalloon = True
.ShowAlways = True
.AutoPopDelay = 5000
.InitialDelay = 1000
.ReshowDelay = 500
.IsBalloon = True
.SetToolTip(Button1, "Click me to execute.")
End With
EDITED:
If you need a fading MessageBox, you can do this:
create a form that accepts a status and a text in constructor
swtich on status drawing correct icon and place text on form
create a timer and on Tick event check if it's time to close
if it's time to close call FadeForm method
Example:
public enum Status
{
None,
Error,
Question,
Warning,
Info
}
public class FadingForm: Form
{
dt: TDateTime;
public FadingForm(Status status, string msg)
{
this.lbl.Text = msg; // I imagine you have a Label named lbl
switch (status)
{
case Warning:
img.Image = warning; // I imagine you have a PictureBox named img
break;
case ...
}
dt = DateTime.Now;
tmr.Enabled = true;
}
public void Tmr_Tick()
{
if (DateTime.Now - dt) > limit
{
FadeForm(10); //Just an example
Close();
}
}
public void FadeForm(byte NumberOfSteps)
{
float StepVal = (float)(100f / NumberOfSteps);
float fOpacity = 100f;
for (byte b = 0; b < NumberOfSteps; b++)
{
this.Opacity = fOpacity / 100;
this.Refresh();
fOpacity -= StepVal;
}
}
}
I think this behavior depends on users windows settings, if you want to achieve this you can code a balloon message your self and decrease its opacity before closing it completely.

Centering DataTip (target) on a ColumnChart in Flex 3

How can I align a DataTip to the vertical center of the corresponding column? I've tried creating a custom dataTipRenderer, but it seems to me that there I can only move the datatip relative to the target (the circle graphic). But that position's just fine, I'd like to move the target itself.
My last idea is to set the showDataTipTargets style of the chart to false and draw the targets within the custom dataTipRenderer. I consider this a dirty hack, so if there's anything more friendly I'd go with that. Plus, in this case, how can I tell the column center coordinates in the datatip renderer's updateDisplayList function?
Hope this snippet of code would help ...
package As
{
import flash.display.*;
import flash.geom.Point;
import mx.charts.*;
import mx.charts.chartClasses.DataTip;
import mx.charts.series.ColumnSeries;
import mx.charts.series.items.ColumnSeriesItem;
public class MyDataTip extends DataTip
{
private var _xBaseLine:int=0;
private var _yBaseLine:int=0;
private var myX = 0
private var myY = 0
public function MyDataTip()
{
super();
}
override public function set data(arg1:Object):void {
var sMessage:String;
var pt:Point;
var hitData:HitData = mx.charts.HitData(arg1);
var chartItem = ColumnSeriesItem(hitData.chartItem);
var renderer = chartItem.itemRenderer;
var series = ColumnSeries(hitData.element);
var colName = chartItem.element.name
var pft = chartItem.xValue
if(renderer != null) {
myX = ( renderer.width / 2 )
myY = ( renderer.height/ 2 ) + ( this.height)
}
super.data=arg1;
}
override public function move (x:Number, y:Number):void {
// Adjusted
var pointAdjusted:Point = new Point(x + _xBaseLine, y + _yBaseLine);
// Call the parent
super.move(pointAdjusted.x, pointAdjusted.y);
}
override protected function updateDisplayList(w:Number, h:Number):void
{
super.updateDisplayList(w, h);
this.x = this.x + myX - 15
this.y = this.y + myY - 7
}
}
}
Cheers !! :)