00.Flex,Flash,ActionScript2013. 5. 28. 13:37
반응형

Using embedded fonts

Rather than rely on a client machine to have the fonts you specify, you can embed TrueType font (TTF) or OpenType font (OTF) families in your Flex application. This means that the font is always available to Flash Player when the application is running, and you do not have to consider the implications of a missing font.

Embedded fonts have the following benefits:

  • Client environment does not need the font to be installed.
  • Embedded fonts are anti-aliased, which means that their edges are smoothed for easier readability. This is especially apparent when the text size is large.
  • Embedded fonts can be partially or fully transparent.
  • Embedded fonts can be rotated.
  • Embedded fonts provide smoother playback when zooming.
  • Text appears exactly as you expect when you use embedded fonts.
  • When you embed a font, you can use the advanced anti-aliasing information that provides clear, high-quality text rendering in SWF files. Using advanced anti-aliasing greatly improves the readability of text, particularly when it is rendered at smaller font sizes. For more information about advanced anti-aliasing, see Using advanced anti-aliasing.

Using embedded fonts is not always the best solution, however. Embedded fonts have the following limitations and drawbacks:

  • Embed only TrueType or OpenType fonts. To embed other font types such as Type 1 PostScript fonts, embed that font in a SWF file that you create in Flash 8, and then embed that SWF file in your Flex application. For more information, see Embedding fonts from SWF files.
  • Embedded fonts increase the file size of your application, because the document must contain font outlines for the text. This can result in longer download times for your users.
  • Embedded fonts, in general, decrease the legibility of the text at sizes smaller than 10 points. All embedded fonts use anti-aliasing to render the font information on the client screen. As a result, fonts may look fuzzy or illegible at small sizes. To avoid this fuzziness, you can use advanced anti-aliasing to render fonts in Flex applications. For more information, see Using advanced anti-aliasing.
  • In some cases, embedded fonts can be truncated when they are used in visual components. In these cases, you might be required to change the padding properties of the component by using style properties or subclassing it. This only occurs with some fonts.

You typically use Cascading Style Sheets (CSS) syntax for embedding fonts in Flex applications. You use the @font-face "at-rule" declaration to specify the source of the embedded font and then define the name of the font by using the fontFamily property. You must specify the @font-face declaration for each face of the font for the same family that you use. The source can be a local Java Runtime Environment (JRE) font or one that is accessible by using a file path. You use this font family name in your MXML code to refer to the embedded font.

Note: Check your font licenses before embedding any font files in your Flex applications. Fonts might have licensing restrictions that preclude them from being stored as vector information.

If you attempt to embed a font that the Flex compiler cannot find, Flex throws an error and your application does not compile.

Embedded font syntax

To embed TrueType or OpenType fonts, you use the following syntax in your style sheet or <mx:Style> tag:

@font-face {
    src: url("location") | local("name");
    fontFamily: alias;
    [fontStyle: normal | italic | oblique;]
    [fontWeight: normal | bold | heavy;]
    [advancedAntiAliasing: true | false;]
}

The src property specifies how the compiler should look for the font and the name of the font to look for. You can load a font either by its filename (by using src:url) or by its system font name (by using src:local). This property is required. For more information, see Locating embedded fonts. The src property also helps determine which font manager the compiler will use; for more information, see About the font managers.

The fontFamily property sets the alias for the font that you use to apply the font in style sheets. This property is required. If you embed a font with a family name that matches the family name of a system font, the Flex compiler gives you a warning. You can disable this warning by setting the show-shadows-system-font-warnings compiler option to false.

The fontStyle and fontWeight properties set the type face values for the font. These properties are optional. The default values are normal.

The advancedAntiAliasing property determines whether to include the advanced anti-aliasing information when embedding the font. This property is optional. The default value is true. You cannot use this option when embedding fonts from a SWF file (see Embedding fonts from SWF files). For more information on using advanced anti-aliasing, see Using advanced anti-aliasing.

The following example embeds the MyriadWebPro.ttf font file:

@font-face {
    src: url("../assets/MyriadWebPro.ttf");
    fontFamily: myFontFamily;
    advancedAntiAliasing: true;
}

The following example embeds that same font, but by using its system font name:

@font-face {
    src: local("Myriad Web Pro");
    fontFamily: myFontFamily;
    advancedAntiAliasing: true;
}

After you embed a font with an @font-face declaration, you can use the value of the fontFamily property, or alias, in a type or class selector. The following example uses myFontFamily, the value of the fontFamily property, as the font in the VBox type selector:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFace.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     @font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFontFamily;
        advancedAntiAliasing: true;
     }
     
     VBox {
        fontFamily: myFontFamily;
        fontSize: 15;
     }     

     Panel {
        paddingLeft: 10;
        paddingTop: 10;
        paddingBottom: 10;
        paddingRight: 10;
     }
  </mx:Style>

  <mx:Panel title="Embedded Font Applied With Type Selector">

     <mx:VBox>
        <!-- This button attempts to use the font of the VBox container. -->
        <mx:Button label="Click Me"/>
        <mx:Label text="This is a label."/> 
        <mx:TextArea width="250">
            <mx:text>
                The text in this TextArea control uses the 
                myClass class selector.
            </mx:text>
        </mx:TextArea>
     </mx:VBox>
  </mx:Panel>

  <!-- This button uses the default font because it is not in
   the VBox. -->
  <mx:Button label="Click Me"/>
    
</mx:Application>

The executing SWF file for the previous example is shown below:

You can also apply the embedded font inline by specifying the alias as the value of the control's fontFamily property, as the following example shows:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFaceInline.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     @font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFontFamily;
        advancedAntiAliasing: true;
     }

     Panel {
        paddingLeft: 10;
        paddingTop: 10;
        paddingBottom: 10;
        paddingRight: 10;
     }
  </mx:Style>

  <mx:Panel title="Embedded Font Applied Inline">
     <mx:VBox fontFamily="myFontFamily">
        <mx:Button label="Click Me"/>
        <mx:Label text="This is a label."/> 
        <mx:TextArea width="200">
            <mx:text>
                The text in the TextArea control is Myriad Web Pro.
            </mx:text>
        </mx:TextArea>
     </mx:VBox>
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

When you run this example, you might notice that the Button control's label uses a system font. This is because the default style of a Button control's label uses a bold typeface. However, the embedded font's typeface (Myriad Web Pro) does not contain a definition for the bold typeface. To have the Button control's label use the proper typeface, you must either embed a font's bold typeface so that the label of a Button control is rendered with the correct font, or change the Button control's typeface to be non-bold. For information on embedding bold typefaces, see Using multiple typefaces.

Locating embedded fonts

The src property in the @font-face declaration specifies the location of the font family. You can specify a url or a local function. The following table describes these functions:

Attribute

Description

url

Embeds a TrueType or OpenType font by location by specifying a valid URI to the font. The URI can be relative (for example, ../fontfolder/akbar.ttf) or absolute (for example, c:/myfonts/akbar.ttf).

local

Embeds a locally accessible TrueType or OpenType font by name rather than location. You use the font name, and not the filename, for the font. For example, you specify "Akbar Bold Italic" rather than "AkbarBI.ttf".

You can embed fonts that are locally accessible by the application server's Java Runtime Environment (JRE). These fonts include the *.ttf files in the jre/lib/fonts folder, fonts that are mapped in the jre/lib/font.properties file, and fonts that are made available to the JRE by the operating system (OS).

On Windows, TTF files in the /windows/fonts directory (or /winnt/fonts) are available to the local function. On Solaris or Linux, fonts that are registered with a font server, such as xfs, are available.

The font name that you specify is determined by the operating system. In general, you do not include the font file's extension, but this is OS-dependent. For more information, consult your operating system documentation.

You must specify the url or local function of the src property in the @font-face declaration. All other properties are optional. In general, you should use url rather than local, because pointing to a file is more reliable than using a reference controlled by the operating system.

Do not mix embedded and nonembedded fonts in the same fontFamily property.

Embedding fonts in ActionScript

You can embed TrueType or OTF font files or system fonts by location or by name by using the [Embed] metadata tag in ActionScript. To embed a font by location, you use the source property in the [Embed] metadata tag. To embed a font by name, you use the systemFont property in the [Embed] metadata tag.

The following examples embed fonts by location by using the [Embed] tag syntax:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFaceActionScriptByLocation.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     .mystyle1 {
        fontFamily:myMyriadFont;
        fontSize: 32pt;
     }
     .mystyle2 {
        fontFamily:myBoldMyriadFont;
        fontSize: 32pt;
        fontWeight: bold;
     }
  </mx:Style>
  
  <mx:Script>
     /* 
      * Embed a font by location. 
      */
     [Embed(source='../assets/MyriadWebPro.ttf', 
        fontName='myMyriadFont', 
        mimeType='application/x-font'
     )] 
     // You do not use this variable directly. It exists so that 
     // the compiler will link in the font.
     private var font1:Class;
     
     /* 
      * Embed a font with bold typeface by location. 
      */
     [Embed(source='../assets/MyriadWebPro-Bold.ttf', 
        fontWeight='bold', 
        fontName='myBoldMyriadFont', 
        mimeType='application/x-font', 
        advancedAntiAliasing='true'
     )] 
     private var font2:Class;
     
  </mx:Script>

  <mx:Panel title="Embedded Fonts Using ActionScript">
     <mx:VBox>
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle1" 
            text="This text uses the MyriadWebPro font." 
            rotation="15"
        />
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle2" 
            text="This text uses the MyriadWebPro-Bold font." 
            rotation="15"
        />
     </mx:VBox>
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

You use the value of the fontName property that you set in the [Embed] tag as the alias (fontFamily) in your style definition.

To embed a font with a different typeface (such as bold or italic), you specify the fontWeight or fontStyle properties in the [Embed] statement and in the style definition. For more information on embedding different typefaces, see Using multiple typefaces.

To show you that the example runs correctly, the Label controls are rotated. If the fonts were not correctly embedded, the text in the Label controls would disappear when you rotated the text.

To embed local or system fonts, you use the system font name rather than the filename for the font. You also specify that name using the systemFont property in the [Embed] tag rather than the source attribute. Otherwise, you use the same syntax, as the following example shows:

<?xml version="1.0"?>
<!-- fonts/EmbeddedFontFaceActionScriptByName.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
  <mx:Style>
     .mystyle1 {
        fontFamily:myPlainFont;
        fontSize: 32pt;
     }
     .mystyle2 {
        fontFamily:myItalicFont;
        fontSize: 32pt;
        fontStyle: italic;
     }
  </mx:Style>
  
  <mx:Script>
     /* 
      * Embed a font by name. 
      */
     [Embed(systemFont='Myriad Web Pro', 
        fontName='myPlainFont', 
        mimeType='application/x-font'
     )] 
     // You do not use this variable directly. It exists so that 
     // the compiler will link in the font.
     private var font1:Class;
     
     /* 
      * Embed a font with italic typeface by name. 
      */
     [Embed(systemFont='Myriad Web Pro', 
        fontStyle='italic', 
        fontName='myItalicFont', 
        mimeType='application/x-font', 
        advancedAntiAliasing='true'
     )] 
     private var font2:Class;
     
  </mx:Script>

  <mx:Panel title="Embedded Fonts Using ActionScript">
     <mx:VBox>
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle1" 
            text="This text uses the plain typeface." 
            rotation="15"
        />
        <mx:Label 
            width="100%" 
            height="75" 
            styleName="mystyle2" 
            text="This text uses the italic typeface." 
            rotation="15"
        />
     </mx:VBox>
  </mx:Panel>
</mx:Application>

The executing SWF file for the previous example is shown below:

To get the system font name in Windows, install the Font properties extension. Then right-click the font's file in Windows Explorer and select the Names tab. Use the value under Font Family Name as the systemFont value.

You can specify a subset of the font's character range by specifying the unicodeRange parameter in the [Embed] metadata tag or the @font-face declaration. Embedding a range of characters rather than using the default of all characters can reduce the size of the embedded font and, therefore, reduce the final output size of your SWF file. For more information, see Setting character ranges.

Using advanced anti-aliasing

When you embed fonts, you can use advanced anti-aliasing to provide those fonts with additional information about the font. Embedded fonts that use the advanced anti-aliasing information are typically clearer and appear sharper at smaller font sizes.

By default, fonts that you embed in Flex applications use the advanced anti-aliasing information. This default is set by the fonts.advanced-anti-aliasing compiler option in the flex-config.xml file (the default value is true). You can override this default value by setting the value in your style sheets or changing it in the configuration file. To disable advanced anti-aliasing in style sheets, you set the advancedAntiAliasing style property to false in your @font-face rule, as the following example shows:

@font-face {
    src:url("../assets/MyriadWebPro.ttf");
    fontFamily: myFontFamily;
    advancedAntiAliasing: false;
}

Using advanced anti-aliasing can degrade the performance of your compiler. This is not a run-time concern, but can be noticeable if you compile your applications frequently or use the web-tier compiler. Using advanced anti-aliasing can also cause a slight delay when you load SWF files. You notice this delay especially if you are using several different character sets, so be aware of the number of fonts that you use. The presence of advanced anti-aliasing information may also cause an increase in the memory usage in Flash Player and Adobe® AIR™. Using four or five fonts, for example, can increase memory usage by approximately 4 MB.

When you embed fonts that use advanced anti-aliasing in your Flex applications, the fonts function exactly as other embedded fonts. They are anti-aliased, you can rotate them, and you can make them partially or wholly transparent.

Font definitions that use advanced anti-aliasing support several additional styles properties: fontAntiAliasType, fontGridFitType, fontSharpness, and fontThickness. These properties are all inheriting styles.

Because the advanced anti-aliasing-related style properties are CSS styles, you can use them in the same way that you use standard style properties, such as fontFamily and fontSize. For example, a text-based component could use subpixel-fitted advanced anti-aliasing of New Century 14 at sharpness 50 and thickness -35, while all Button controls could use pixel-fitted advanced anti-aliasing of Tahoma 10 at sharpness 0 and thickness 0. These styles apply to all the text in a TextField control; you cannot apply them to some characters and not others.

The default values for the advanced anti-aliasing styles properties are defined in the defaults.css file. If you replace this file or use another style sheet that overrides these properties, Flash Player and AIR use the standard font renderer to render the fonts that use advanced anti-aliasing. If you embed fonts that use advanced anti-aliasing, you must set the fontAntiAliasType property to advanced, or you lose the benefits of the advanced anti-aliasing information.

The following table describes these properties:

Style property

Description

fontAntiAliasType

Sets the antiAliasType property of internal TextField controls. The valid values are normal and advanced. The default value is advanced, which enables advanced anti-aliasing for the font.

Set this property to normal to prevent the compiler from using advanced anti-aliasing.

This style has no effect for system fonts or fonts embedded without the advanced anti-aliasing information.

fontGridFitType

Sets the gridFitType property of internal TextField controls. The valid values are none, pixel, and subpixel. The default value is pixel. For more information, see the TextField and GridFitType classes in the Adobe Flex Language Reference.

This property has the same effect as the gridFitType style property of the TextField control for system fonts, only it applies when you embed fonts with advanced anti-aliasing.

Changing the value of this property has no effect unless the fontAntiAliasType property is set to advanced.

fontSharpness

Sets the sharpness property of internal TextField controls. The valid values are numbers from -400 to 400. The default value is 0.

This property has the same effect as the fontSharpness style property on the TextField control for system fonts, only it applies when you embed fonts with advanced anti-aliasing.

Changing the value of this property has no effect unless the fontAntiAliasType property is set to advanced.

fontThickness

Sets the thickness property of internal TextField controls. The valid values are numbers from -200 to 200. The default value is 0.

This property has the same effect as the fontThickness style property on the TextField control for system fonts, only it applies when you embed fonts with advanced anti-aliasing.

Changing the value of this property has no effect unless the fontAntiAliasType property is set to advanced.

Detecting embedded fonts

You can use the SystemManager class's isFontFaceEmbedded() method to determine whether the font is embedded or whether it has been registered globally with the register() method of the Font class. The isFontFaceEmbedded() method takes a single argument--the object that describes the font's TextFormat--and returns a Boolean value that indicates whether the font family you specify is embedded, as the following example shows:

<?xml version="1.0"?>
<!-- fonts/DetectingEmbeddedFonts.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
     creationComplete="determineIfFontFaceIsEmbedded()">
  <mx:Style>
     @font-face {
        src: url(../assets/MyriadWebPro.ttf);
        fontFamily: myPlainFont;
        advancedAntiAliasing: true;
     }
     
     .myStyle1 {
        fontFamily: myPlainFont; 
        fontSize:12pt
     }
  </mx:Style>
  <mx:Script><![CDATA[
     import mx.managers.SystemManager;
     import flash.text.TextFormat;
     
     public function determineIfFontFaceIsEmbedded():void {
        var tf1:TextFormat = new TextFormat();
        tf1.font = "myPlainFont";
        
        var tf2:TextFormat = new TextFormat();
        tf2.font = "Arial";
        
        var b1:Boolean = Application.application.systemManager.
           isFontFaceEmbedded(tf1);
        var b2:Boolean = Application.application.systemManager.
           isFontFaceEmbedded(tf2);
        l1.text = tf1.font + " (" + b1 + ")";
        l2.text = tf2.font + " (" + b2 + ")";
     }
  ]]></mx:Script>
  <mx:Text id="text1" styleName="myStyle1" text="Rotate Me"/>

  <mx:HBox>
    <mx:Button label="Rotate +1" click="++text1.rotation;"/>
    <mx:Button label="Rotate -1" click="--text1.rotation;"/>
  </mx:HBox>

  <mx:Form>
     <mx:FormItem label="isFontFaceEmbedded:">
        <mx:Label id="l1"/>
     </mx:FormItem>         
     <mx:FormItem label="isFontFaceEmbedded:">
        <mx:Label id="l2"/>
     </mx:FormItem>         
  </mx:Form>    
</mx:Application>

The executing SWF file for the previous example is shown below:

You can use the Font class's enumerateFonts() method to output information about device or embedded fonts. The following example lists embedded fonts:

<?xml version="1.0"?>
<!-- fonts/EnumerateFonts.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" creationComplete="listFonts()">
  <mx:Style>
     @font-face {
        src:url("../assets/MyriadWebPro.ttf");
        fontFamily: myFont;
        advancedAntiAliasing: true;
     }

     @font-face {
        src:url("../assets/MyriadWebPro-Bold.ttf");
        fontFamily: myFont;
        fontWeight: bold;
        advancedAntiAliasing: true;
     }

     @font-face {
        src:url("../assets/MyriadWebPro-Italic.ttf");
        fontFamily: myFont;
        fontStyle: italic;
        advancedAntiAliasing: true;
     }
     
     .myPlainStyle {
        fontSize: 20;
        fontFamily: myFont;
     }
     
     .myBoldStyle {
        fontSize: 20;
        fontFamily: myFont;
        fontWeight: bold;
     }

     .myItalicStyle {
        fontSize: 20;
        fontFamily: myFont;
        fontStyle: italic;
     }
  </mx:Style>

  <mx:Script><![CDATA[
     private function listFonts():void {
        var fontArray:Array = Font.enumerateFonts(false);
        for(var i:int = 0; i < fontArray.length; i++) {
           var thisFont:Font = fontArray[i];
           if (thisFont.fontType == "embedded") {
              ta1.text += "FONT " + i + ":: name: " + thisFont.fontName + "; typeface: " + 
                thisFont.fontStyle + "; type: " + thisFont.fontType + "\n";
           }
        }
     }
  ]]></mx:Script>

  <mx:HBox borderStyle="solid"> 
     <mx:Label text="Plain Label" styleName="myPlainStyle"/> 
     <mx:Label text="Bold Label" styleName="myBoldStyle"/> 
     <mx:Label text="Italic Label" styleName="myItalicStyle"/> 
  </mx:HBox>

  <mx:TextArea id="ta1" height="200" width="400"/>

</mx:Application>

The executing SWF file for the previous example is shown below:

The following list shows the output.

name: myFont; typeface: regular; type: embedded
name: myFont; typeface: bold; type: embedded
name: myFont; typeface: italic; type: embedded

The enumerateFonts() method takes a single Boolean argument: enumerateDeviceFonts. The default value of the enumerateDeviceFonts property is false, which means it returns an Array of embedded fonts by default.

If you set the enumerateDeviceFonts argument to true, the enumerateFonts() method returns an array of available device fonts on the client system, but only if the client's mms.cfg file sets the DisableDeviceFontEnumeration property to 0, the default value. If you set the DisableDeviceFontEnumeration property to 1, Flash Player cannot list device fonts on a client computer unless you explicitly configure the client to allow it. For more information about configuring the client with the mms.cfg file, see the Flash Player documentation.

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 13:18
반응형
2009.1.21 : 데이타가 너무 촘촘하게 붙는 경우 직선과 차이가 없어지는 문제로, 수정하였습니다.

This is a DashLine Line Segment Renderer for Flex Chart. (Tested in FLEX 3.0)
You must modify the package & class path.


Click this icon to download the source.
모자이크 부분은 고객사 로고 때문임..;; (Don't care the mossaic)

LineSeries 에서 점선을 사용해야 해서 만들게 된 Dash Line Renderer이다.
해당 클래스만 넣었으므로 Class Path는 적절히 고쳐서 사용할 것.


사용법은 LineChart 등에 쓰이는 LineSeries에 lineSegmentRenderer 값으로 해당 Class Path를 쓰면 된다.
예를 들어

component.LineRenderer.DotLine01 로 넣었다면

<mx:LineSeries lineSegmentRenderer="component.LineRenderer.DotLine01" ..... />
이렇게 넣으면 된다.


다운 받은 걸 열어보면 DotLineBase.as 와 DotLine01.as 가 있는데 DotLine01.as 를 복제해 가며 점선의 종류를 늘려 가면 된다.

개별 Class에서 설정 가능한 옵션은

gap=6; // 점선 사이 간격
length=6; // 점선 길이
lineWeight=3; // 선 굵기
lineAlpha=1; // 선 알파


이다.

선 색은 기본적으로 시리즈에 정의된 선 색을 쓰게 된다.

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 11:23
반응형
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="horizontal">
   
<mx:DateFormatter id="df" formatString="JJ:NN:SS" />
   
<mx:Script>
        <![CDATA[
            private const minimum:Date = new Date( "Apr 1 2011 01:03:54 AM");
            private const maximum:Date = new Date( "Apr 1 2011 03:07:54 AM");
            private function labelFunction(item:Object,
                                           field:String,
                                           index:Number):String {
                return df.format(item as Date);
            }
        ]]>
   
</mx:Script>

   
<mx:CartesianChart width="600" height="200">

       
<mx:horizontalAxis>
           
<mx:DateTimeAxis
               
minimum = "{minimum}"
               
maximum = "{maximum}"
               
displayLocalTime="true"
               
labelFunction="labelFunction"
               
labelUnits="minutes"
           
/>
           
<!--
                interval="15"
            -->

       
</mx:horizontalAxis>

   
</mx:CartesianChart>

</mx:Application>

Gives this flex screenshot

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 28. 11:01
반응형

The DateFormatter is a very simple formatter. To use it you just have to specify the formatString property, apply the format and you are done.

<mx:DateFormatter formatString="Y|M|D|A|E|H|J|K|L|N|S"/>

Here are some short explanations of what the characters in formatString represent:

Y – Year
M – month
D – Day
A – AM/PM indicator
E – day of the week
H – Hour (1-24 hours format)
J – Hour (0-23 hours format)

K – Hour in am/pm (0-11 hours format)
L – Hour in am/pm (1-12 hours format)
N – Minutes
S – Seconds

The formatString may also contain other words as separators between Y, M, D, A etc. as we will see in the example below.

Here is an example that uses the Flex DateFormatter Class

<?xml version="1.0" encoding="utf-8"?>
<!--http://www.popamihai.com/2009/07/flex/example-of-using-the-dateformatter-class-in-flex/-->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical" backgroundColor="white" 
	creationComplete="formatDates()" viewSourceURL="srcview/index.html">
 
	<mx:Script>
		<![CDATA[
			private function formatDates():void{
				dateFormatter.formatString = "DD/MM/YY";
				formattedDate1.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEE DD/MM/YY";
				formattedDate2.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD/MM/YY";
				formattedDate3.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMM YYYY";
				formattedDate4.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY";
				formattedDate5.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN";
				formattedDate6.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN A";
				formattedDate7.text = dateFormatter.format(initialDate.text);
				dateFormatter.formatString = "EEEE DD MMMM YYYY at HH:NN.SS A";
				formattedDate8.text = dateFormatter.format(initialDate.text);
			}
		]]>
	</mx:Script>
 
	<mx:DateFormatter id="dateFormatter" />
 
	<mx:Text text="Change The Initial Date And Format The New Dates" fontWeight="bold"/>
 
	<mx:Form>
		<mx:FormItem label="Initial Date:" >
			<mx:TextInput id="initialDate" text="01.01.2009 10:34 57" />
		</mx:FormItem>
		<mx:FormItem label="DD/MM/YY" >
			<mx:TextInput id="formattedDate1" />
		</mx:FormItem>
		<mx:FormItem label="EEE DD/MM/YY" >
			<mx:TextInput id="formattedDate2" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD/MM/YY" >
			<mx:TextInput id="formattedDate3" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMM YYYY" >
			<mx:TextInput id="formattedDate4" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY" >
			<mx:TextInput id="formattedDate5" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY at HH:NN" >
			<mx:TextInput id="formattedDate6" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY at HH:NN A" >
			<mx:TextInput id="formattedDate7" />
		</mx:FormItem>
		<mx:FormItem label="EEEE DD MMMM YYYY at HH:NN.SS A" >
			<mx:TextInput id="formattedDate8" />
		</mx:FormItem>
		<mx:FormItem >
			<mx:Button click="formatDates()" label="format dates"/>
		</mx:FormItem>
	</mx:Form>
</mx:Application>

In the following example the formatString is displayed on the left column, and the formatted dates are displayed in the TextInput controls from the right column. To see how the different formats work change the “Initial Date” with a valid date and press the “format dates” button.

View Source is enabled in the above example. To view the source files right click on the swf and choose “View Source” from the context menu.

 

Posted by 1010
반응형
[펌]오라클 날짜 계산
출처 : http://www.zetswing.com/bbs/board.php?bo_table=ORACLE_TIP&wr_id=20&page=

1. Oracle에서의 날짜 특징

*oracle은 세기,년,월,일,시간,분,초의 내부숫자 형식으로 날짜를 저장합니다.
*디폴트 날짜형식은 'DD-MON-YY' 입니다.
*SYSDATE는 현재의 날짜와 시간을 리턴하는 함수입니다.(date타입)
ex : 2007-01-07 오후 10:34:00
*DUAL은 SYSDATE를 보기위해 사용된 dummy table입니다.

2.oracle에서의 날짜연산

* 날짜에서 숫자(날수)를 빼거나 더하여 날짜 결과를 리턴합니다. 결과는 날짜형식
* 날짜 사이의 일수를 알기 위하여 2개의 날짜를 뺍니다.
* 시간을 24로 나누어 날짜에 더합니다.
날짜 + 숫자 : 날짜 특정한 날로부터 몇일 후의 날짜 계산
날짜 - 숫자 : 날짜 특정한 날로부터 몇일 전의 날짜 계산
날짜 - 날짜 : 숫자 두 날짜 사이의 차이를 숫자로 계산

3.oracle에서의 날짜 컬럼데이타형

date 형

4. 월과 일을 문자로 출력시 한글로 나오는거 영문으로 나오게 하기

오라클 환경 설정에 따라 아래 쿼리를 실행시키면 "7월" 이라고 나올수 있다.
SELECT TO_CHAR(SYSDATE,'mon') FROM DUAL;

오라클 환경 설정에 따라 아래 쿼리를 실행시키면 "월요일" 이라고 나올수 있다.
SELECT TO_CHAR(sysdate,'day') FROM DUAL;

영문("Jul")으로 출력시키려면 아래 명령으로 환경설정을 변경한다.
ALTER SESSION SET NLS_LANGUAGE = 'AMERICAN';

※ 월요일, 화요일 형식이 아닌 월, 화 형식으로 나타내기
SELECT TO_CHAR(sysdate,'day') FROM DUAL;

5.날짜의 순서결과 데이타형

날짜 - 날짜 = 숫자
숫자 + 날짜 = 날짜
(날짜 - 날짜) + 날짜 = 날짜
날짜 + 날짜 = error


※ trunc함수를 날짜데이타에 사용하기

select sysdate from dual;
--2006-02-08 오전 12:11:05


select trunc(sysdate) from dual;
select trunc(sysdate,'dd') from dual;
--단지 시간을 없애고 날짜만 나오게 한다.
--2006-02-08


select trunc(sysdate,'d') from dual;
--시간을 없애고 일을 가장최근에 지난 일요일 일로 초기화합니다.(권장)
--2006-02-05


select trunc(sysdate,'d')+1 from dual;
--시간을 없애고 일을 가장최근에 지난 월요일 일로 초기화합니다.

select trunc(sysdate,'d')-1 from dual;
--시간을 없애고 일을 가장최근에 지난 토요일 일로 초기화합니다.


select trunc(sysdate,'ww') from dual;
--시간을 없애고 일을 가장최근에 지난 일요일 일로 초기화합니다.
--2006-02-05


select trunc(sysdate,'mm') from dual;
--시간을 없애고 일을 1로 초기화합니다.
--2006-02-01


select trunc(sysdate,'Y') from dual;
select trunc(sysdate,'YY') from dual;
select trunc(sysdate,'YYY') from dual;
select trunc(sysdate,'YYYY') from dual;
--시간을 없애고 년도는 올해 년도와 월과 일을 모두 1 로 변경하여 출력합니다.

ex. 2006-01-01

SELECT TO_CHAR(SYSDATE,'YYYYMMDD') FROM DUAL;
SELECT TO_CHAR('20070715') FROM DUAL;
-- 현재 날짜를 YYYYMMDD 형식으로 출력한다.(자주사용)

8자리일자와 6자리시간을 문자열로 출력
select
to_char(sysdate, 'yyyymmdd') ,
to_char(sysdate, 'hh24miss')
from dual

6.날짜 관련 쿼리 예제

해당일이 그달의 몇째주인지 알아내기(w)
SELECT to_char(to_date('20061224', 'yyyymmdd'), 'w') FROM dual;

해당년도의 전체 일수 구하기
SELECT to_date('20001231', 'YYYYMMDD') - to_date('20000101', 'YYYYMMDD') from dual
SELECT TO_CHAR (TO_DATE (:yyyy || '1231'), 'ddd') ilsu FROM DUAL
-- 위의 쿼리는 년도를 변수로 사용하였다.


UPDATE tab1 SET logdate = sysdate, ismodify = 1 WHERE logdate < sysdate-7
--기록된 날짜(LOGDATE)가 현재날짜(SYSDATE)로부터 일주일이 지났으면
--SYSDATE를LOGDATE에 쓰고 날짜가 바뀌었다는 기록을 남기는(ISMODYFY = 1) 쿼리

UPDATE tab1 SET logdate = sysdate, ismodify = 1 WHERE logdate < TRUNC(sysdate,'d')
기록된 날짜(LOGDATE)가 일요일이 한번이라도 지났다면, 즉 이번주 일요일부터 토요일간의 기록이라면 그대로 두고 그 이상 오래된 경우 현재날짜(SYSDATE)를 LOGDATE에 남기는 쿼리

select ename,job,hiredate from emp where hiredate between '1981-02-20' and '1981-05-01';
--1981년02월20일부터 1985년05월01일까지의 레코드를 검색한다.(꼭옛날날짜에서최근날짜로검색)


select ename,(sysdate - hiredate)/7 week from emp;
--sysdate함수로 현재 날짜시간에서 입사날짜(hiredate)를 빼면 일수가나오고 거기서 7을 나누어

--근무한 주수를 알수있습니다.

select * from emp where hiredate='1980/12/17';
--날짜 비교는 ''을 이용하여 비교합니다.


select months_between(sysdate,hiredate)/12 ,hiredate from emp;
--오늘날짜에서 입사날짜를 빼서 달수를 구한후 12을 나누어 근무한 년수를 구할수있다.


select months_between(to_date(20011129,'yyyymmdd'),to_date(20020228,'yyyymmdd')) from dual;
--첫번째 날짜에서 두번째 날짜를 빼서 달수로 구한다.

select round(months_between(sysdate,hiredate)/12) ,hiredate from emp;
--소수점이 있는 결과에서 반올림합니다.

select trunc(months_between(sysdate,hiredate)/12) ,hiredate from emp;
--소수점이 있는 결과에서 버림합니다.


ADD_MONTHS 함수예제

SELECT ADD_MONTHS(HIREDATE,2) FROM EMP;
-- HIREDATE값에 2달를 더하여 출력

SELECT TO_CHAR(ADD_MONTHS(SYSDATE,-1), 'YYYYMMDD'),
TO_CHAR(SYSDATE-30, 'HH24MIDD') FROM DUAL;
-- DATE형 현재 날짜시간에서 1달을 뺀후 출력

SELECT TO_CHAR(ADD_MONTHS(TO_DATE('20060907230000','YYYYMMDDHH24MISS'),
-1),'YYYYMMDDHH24MI') FROM DUAL;
-- CHAR형 현재 날짜시간에서 1달을 뺀후 출력

select add_months(to_date('200706'||'01','yyyymmdd'),-1) from dual
-- 20070601에서 한달을 뺍니다.

select add_months(hiredate,-2) from emp;
--입사날짜에서 2달을 빼서 출력합니다.


select hiredate+100 from emp;
--입사날짜에서 100일을 더합니다.


select hiredate-100 from emp;
--입사날짜에서 100일을 뺍니다.


LAST_DAY() 함수
해당 날짜에 달에 마지막 일의 날짜를 출력한다.
사용예제
SELECT LAST_DAY('2006-05-05') FROM DUAL;
--2006-05-31

SELECT LAST_DAY(SYSDATE) FROM DUAL;
--2006-05-31 오후 10:35:51


※oracle에서는 날짜함수에(sysdate) 산술연산이 가능합니다.
1일->1
1시간->1/24
1분->1/24/60
1초->1/24/60/60

select sysdate-1 from dual;
--지금 시간 기준으로 1일전


select sysdate-(1/24) from dual;
--지금 시간 기준으로 1시간전


select sysdate+1/24/60*1 from dual;
--지금 시간 기주으로 1분전


select sysdate+1/24/60*10 from dual;
--지금 시간 기주으로 10분전


select to_date(200611210800,'yyyymmdd hh24miss')+ 10/24 from duaL;
--10시간을 더한다.


select to_char(to_date('2005-05-05'),'d') from account;
--날짜를 숫자형식의 요일로 출력(1-일요일,7-토요일)

select to_char(to_date('2005-05-05'),'day') from account;
--날짜를 알파벳요일로 출력

select to_char(to_date('2005-05-05'),'year') from account;
--날짜를 알파벳년도로 출력


select to_char(to_date('2005-05-05'),'month') from account;
-- 월을 영문으로 완벽하게 출력


select to_char(to_date('2005-05-05'),'mon') from account;
-- 월을 영문 앞 3글자만 출력


select decode(to_char(to_date('2005-05-05'),'d'),
'2','1',
'3','2',
'4','3',
'5','4',
'6','5',
'7','6',
'1','7') "요일"
from dual;

--날짜의 요일을 숫자로 출력(1-월요일,7-일요일)

DATE형 컬럼 비교시

SELECT * FROM TABLE_NAME WHERE FDATE < to_date('20070711','YYYYMMDD')

6. 프로그래밍 언어에서 날짜 검색시 방법

날짜 관련 컬럼은 DATE, CHAR(8), NCHAR(8)을 주지만 DATE는 7바이트이다.

DATE형은 아래와 같이 검색 조건을 사용한다.

WHERE A_DATE BETWEEN '2005-10-10' AND '2005-10-30';
WHERE A_DATE BETWEEN TO_DATE('2005-10-10') AND TO_DATE('2005-10-30');

CHAR(8), NCHAR(8)형은 아래와 같이 검색조건을 사용한다.

WHERE A_DATE BETWEEN '20051010' AND '20051030';

두가지의 장단점을 알아보자

7. 해당 시간이 현재 24시간이 지났는지 알수 있는 쿼리

SELECT CASE WHEN SYSDATE - TO_DATE('20070727','YYYYMMDD') >= 1
THEN 'Y' ELSE 'N' END RESUAL FROM DUAL;
※ SYSDATE가 날짜형이므로 빼주는 값도 날짜형이어야 합니다.

SELECT round(to_date('95/05/25'),'DAY')
FROM dual
1995/05/28 00:00:00
SELECT TRUNC(TO_DATE('95/05/25'), 'DAY')
FROM dual
1995/05/21 00:00:00

문제는 day 함수에 있습니다.
day함수는 요일을 나타내죠.
따라서 to_date('95/05/25')를 day로 표시하면 수요일이 나옵니다.
위에 쿼리는 그걸 반올림하였으니 그 주에 가장 큰 28일이 나왔구요,
아래 쿼리는 그걸 잘라내버렸으니 그 주에 가장 작은 21일이 나온 겁니다.

SELECT SYSDATE + 2/24 FROM DUAL;
-- 현재시간의 2시간후에 시간을 출력
SELECT SYSDATE - 2/24 FROM DUAL;
-- 현재시간의 2시간전의 시간을 출력

select to_char(trunc(sysdate), 'rrrr/mm/dd') A from dual;
select to_char(trunc(sysdate), 'yyyy/mm/dd') A from dual;
YYYY포맺은 현재를 기준으로 합니다.
RRRR기준은 .년도의 뒷자리를 기준으로
2000년도 기준으로 보면
0-49 년은 after year 35/12/12 ->2055/12/12
50-99 년은 before year 51/12/12 ->1951/12/12
가 됨니다.

8. 날짜 관련 함수

SYSDATE 함수
? 현재 시스템 날짜를 출력
SELECT SYSDATE FROM DUAL;
-- ORACLE 10g XE 에서 출력되는 날짜형식
-- 2008-05-17 오후 5:15:17

LAST_DAY 함수
? 해당 날짜의 달에서 마지막 일을 출력
SELECT LAST_DAY(SYSDATE) FROM DUAL;
--2008-05-31 오후 5:16:54

 

Posted by 1010
반응형

SQL - Timestamp
A timestamp servers as the catch all for dates and times. Retrieving a timestamp is very simple and the result can be converted or manipulated in nearly every way imaginable.


SQL Code:
SELECT CURRENT_TIMESTAMP;
Return a Timestamp:2004-06-22 10:33:11.840
Keep in mind that each platform of SQL (DB2, Oracle, SQL Server, etc...) may return dates and times which are formatted differently.
SQL- Date FunctionsAs we just mentioned, it is possible to breakdown timestamps into their individual pieces using any of the following date functions.

SQL Code:
SELECT MONTH(CURRENT_TIMESTAMP);
Return a Month:6 SQL Code:
SELECT DAY(CURRENT_TIMESTAMP);
Return a Day:22

There are many more functions available, including functions to extract milliseconds, names of the months, names of each week day, etc.
Each SQL platform varies in the actual naming of date functions. Here's a few c\The following is a list of other date functions available to most platforms of SQL with the exception of MS's SQL Server.

SQL Function Code:
SELECT DATE(CURRENT_TIMESTAMP); - returns a date (2004-06-22)
SELECT TIME(CURRENT_TIMESTAMP); - returns the time (10:33:11.840)
SELECT DAYOFWEEK(CURRENT_TIMESTAMP); - returns a numeric value (1-7)
SELECT DAYOFMONTH(CURRENT_TIMESTAMP); - returns a day of month (1-31)
SELECT DAYOFYEAR(CURRENT_TIMESTAMP); - returns the day of the year (1-365)
SELECT MONTHNAME(CURRENT_TIMESTAMP); - returns the month name (January - December
SELECT DAYNAME(CURRENT_TIMESTAMP); - returns the name of the day (Sunday - Saturday)
SELECT WEEK(CURRENT_TIMESTAMP); - returns number of the week (1-53)


Timestamps are often the easiest to work with, but we certainly are not limited to using only the current_timestamp as our parameter. We can send any date, time, or timestamp to the function which then returns our result.

SQL Code:
SELECT MONTHNAME('2004-11-27');
Return a Month Name: MONTHNAME('2004-11-27') November
Date functions can also be performed on table columns similarly to numeric and mathematical functions such as SUM() or AVG().

SQL Code:
SELECT DAYOFYEAR(column_name) FROM table_name WHERE name = 'Joe';
SQL will return a numeric result from 1 - 365 representing the day of the year that Joe's record was created/inserted.We can expand this concept one step further with the use of a subquery. Say we have a table with a column named timestamp. In this table column are timestamps of when each record was entered and we would like to know what was the numeric day of the year that a record was entered.

SQL Code:
SELECT DAYOFYEAR((SELECT DATE(timestamp) FROM employees WHERE name = 'James Bond'));
Above you can see how it is possible to combine several date functions as well as a subquery to return very specific information about Mr. James Bond.
SQL - Inserting Date DataDate data exists as numbers, strings, and timestamps. Built into most platforms are several date column types such as DATE or TIMESTAMP. By setting the default value to the current date or timestamp, the table column will automatically be filled with a current date/timestamp as each record is inserted.
Here's the code to add a timestamp column to an existing table.
SQL Code:
ALTER TABLE `orders` ADD `order_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL;
Now each time an order is placed in our make believe business, a timestamp of that order is also recorded.A date or timestamp table column will only allow date data types to be inserted as values so be sure to convert any strings or numbers to dates and timestamps before trying to insert them.

SQL - Datepart()

Microsoft's SQL Server takes a little different approach to working with dates. It is still possible to extract individual parts of a timestamp and several other functions also work as outlined in SQL - Date. The difference is that SQL Server uses one main function as oppose to several different functions ie the DATEPART() function.
Datepart() requires two parameters, a part argument and a date argument. By part we mean year, day of the year, day of the week, etc. Let's look at an example.

SQL Code:
SELECT DATEPART(week, '2005-12-31');Return the Week Number:53

Here we have successfully pulled the "week number" from existing date.
SQL's CURRENT_DATE function could be also be substituted or a string value representing the year ('Dec 31, 2005').

Posted by 1010
반응형

–1시간 더하기

select to_char(to_date(’121212′,’hh24miss’)+1/24,’hh24:mi:ss’) from dual;

–30분 더하기

select to_char(to_date(’121212′,’hh24miss’)+30/24/60,’hh24:mi:ss’) from dual;

select to_char(to_date(’121212′,’hh24miss’)+30/(24*60),’hh24:mi:ss’) from dual;

–40초 더하기

select to_char(to_date(’121212′,’hh24miss’)+40/24/60/60,’hh24:mi:ss’) from dual;

select to_char(to_date(’121212′,’hh24miss’)+40/(24*60*60),’hh24:mi:ss’) from dual;

–12시간 58분 58초 더하기

select to_char(to_date(’121212′,’hh24miss’)+12/24 + 58/24/60 + 58/24/60/60,’hh24:mi:ss’) from dual;

– 시: 분: 초 가져오기

select substr(’125858′,1,2), substr(’125858′,3,2), substr(’125858′,5,2) from dual;

[참고] http://julymorning.co.kr/xe/index.php?document_srl=3798&mid=tiptech_prog

 

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 22. 09:33
반응형
Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 20. 14:12
반응형

출처 : http://flexponential.com/2009/09/23/deleting-items-in-a-list-from-an-item-renderer/

 

It’s easy to delete an item in a spark List from within an item renderer. This is handy if you have a List with a custom renderer that provides a button to delete the item that is associated with that renderer.

You can do this by using the ItemRenderer’s owner property to access the List it is in, drill down to its dataProvider and delete the data item:

<s:ItemRenderer>
    <fx:Script>
        <![CDATA[
                import spark.components.List;
                public function deleteItem():void {
                    var parentList:List = owner as List;
                    // remove the item
                    parentList.dataProvider.removeItemAt(parentList.dataProvider.getItemIndex(data))
                }
            ]]>
        </fx:Script>
        <s:HGroup>
            <s:Label text="{data}" />
            <s:Button id="remove" label="X"  click="deleteItem()"/>
        </s:HGroup>
</s:ItemRenderer>

Another approach is to delete items based on the selectedItem/selectedIndex, but I prefer this method since it allows you to delete items without needing to select them.

Here is an example that uses the deleteItem() method listed above:

View Source

This should work the same way for DataGroup and SkinnableDataContainer as well.

Note: This sample requires Flex SDK 4.0.0.10545 or higher. You can get the latest SDK builds from opensource.adobe.com.

Posted by 1010
00.Flex,Flash,ActionScript2013. 5. 20. 13:52
반응형

<init시 itemrenderer를 갖고 있는 start_addr_deny(datagrid)에 접근할 addEventListener추가>

private function init():void{
start_addr_deny.addEventListener("status_bt", status_btHandler);

}

<dispatchEvent를 이용한 클릭시 외부 접근>

<mx:DataGridColumn id="check_Add" width="50">
<mx:itemRenderer>
<mx:Component>
<mx:HBox horizontalAlign="center">
<mx:CheckBox click="dispatchEvent(new Event('status_bt', true))"/>
</mx:HBox>
</mx:Component>
</mx:itemRenderer>
</mx:DataGridColumn>

Posted by 1010