myBlog

IronPython, Silverlight, WPF, XAML, HTML5, ...

IronPythonで、Loose XAML を実行する for Google Chrome12

2011-07-08 13:03:44 | DataBinding
IronPythonで、Loose XAMLファイルを実行する。
Google Chrome12 では、読み込むとエラーになるので、作ってみました。

Loose XAML⇒DropShadowInk.xamlDrop-shadows are cool!

LooseXaml.py: LoosXAMLをIronPythonで、ラップしました。
LooseXaml2.py: ローカルファイルのLooseXAMLをIronPythonで、読み込み実行。
LooseXaml3.py: インターネットにあるLooseXAMLをIronPythonで、読み込み実行。

Loosexaml   

#
# LooseXaml.py
# ipy.exe LooseXaml.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader
xaml_str="""
<Page WindowTitle = "Binding ( Slider, Rectangle )"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid
        Background="OrangeRed" Width="300" Height="300" >
        <Slider x:Name = "MySlider" 
            VerticalAlignment = "Top" 
            Minimum = "10" 
            Maximum = "200" 
            Value = "50" 
            Margin = "10" />
        <Rectangle 
            Width = "{Binding ElementName = MySlider, Path = Value}" 
            Height = "{Binding ElementName = MySlider, Path = Value}" 
            Fill = "Orange"
            VerticalAlignment = "Center"
            HorizontalAlignment = "Center" />
    </Grid>
</Page>
"""
class Window1(Window):
    def __init__(self):
       self.Content = XamlReader.Parse(xaml_str)
if __name__ == "__main__":
    win = Window1()
    Application().Run(win)

#
# LooseXaml2.py
# ipy.exe LooseXaml2.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader

def LoadXaml(filename):
    from System.IO import *
    from System.Windows.Markup import XamlReader
    f = FileStream(filename, FileMode.Open, FileAccess.Read)
    try:
        element = XamlReader.Load(f)
    finally:
        f.Close()
    return element
class Window1(Window):
    def __init__(self):
       self.Content = LoadXaml("LooseXaml.xaml")
if __name__ == "__main__":
    win = Window1()
    Application().Run(win)

#
# LooseXaml3.py
# ipy.exe LooseXaml3.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System import Uri, UriKind
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader

def LoadXaml3(strUrl):
    import System
    # Create a request for the URL. 
    request = System.Net.WebRequest.Create(strUrl)
    # If required by the server, set the credentials.
    #request.Credentials = System.Net.CredentialCache.DefaultCredentials
    # Get the response.
    response = request.GetResponse()
    # Get the stream containing content returned by the server.
    dataStream = response.GetResponseStream()
    try:
        element = XamlReader.Load(dataStream)
    finally:
        # Cleanup the streams and the response.
        dataStream.Close()
        response.Close()
    return element

class Window1(Window):
    def __init__(self):
      self.Content = LoadXaml3("http://softgarden.lovepop.jp/myBlog/xaml/dropshadowink.xaml")

if __name__ == "__main__":
    win = Window1()
    Application().Run(win)

GitHubにプログラムを投稿しています。参考にしてください。
https://github.com/softgarden137/LooseXAML

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、MouseEnterで図形が動きだすAnimation

2011-07-07 12:30:13 | Animation
IronPythonで、MouseEnterで図形が動きだすAnimationを紹介します。
Googleで検索していると、おもしろいアニメーションXAMLを見つけました。
Blog: "++C++;// 未確認飛行 C" ⇒ アニメーション(WPF)⇒ MouseEnter.xaml
http://ufcpp.net/study/dotnet/wpf_xamlani.html
さっそく、IronPythonで実行できるようにしてみました。

#
# MouseEnterAnimation.py

import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader
xaml_str="""
<WrapPanel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="200" Height="200">
    <WrapPanel.Resources>
        <Style TargetType="{x:Type Rectangle}">
            <Setter Property="Fill" Value="#8080ff"/>
            <Setter Property="Width" Value="50"/>
            <Setter Property="Height" Value="50"/>
            <Setter Property="RenderTransform">
                <Setter.Value>
                    <RotateTransform CenterX="25" CenterY="25" Angle="0"/>
                </Setter.Value>
            </Setter>
            <Style.Triggers>
                <EventTrigger RoutedEvent="Mouse.MouseEnter">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation
                                Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
                                To="#ff8080"
                                Duration="0:0:0"/>
                            <DoubleAnimation
                                Storyboard.TargetProperty="RenderTransform.Angle"
                                To="0"
                                Duration="0:0:0"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Mouse.MouseLeave">
                    <BeginStoryboard>
                        <Storyboard>
                            <ColorAnimation
                                Storyboard.TargetProperty="(Shape.Fill).(SolidColorBrush.Color)"
                                To="#8080ff"
                                Duration="0:0:1"/>
                            <DoubleAnimation
                                Storyboard.TargetProperty="RenderTransform.Angle"
                                To="360"
                                Duration="0:0:3"/>
                        </Storyboard>
                    </BeginStoryboard>
                </EventTrigger>
            </Style.Triggers>
        </Style>
    </WrapPanel.Resources>
    <Rectangle/><Rectangle/><Rectangle/><Rectangle/>
    <Rectangle/><Rectangle/><Rectangle/><Rectangle/>
    <Rectangle/><Rectangle/><Rectangle/><Rectangle/>
    <Rectangle/><Rectangle/><Rectangle/><Rectangle/>
</WrapPanel>
"""
class Window1(Window):
    def __init__(self):
        self.Title = "MouseEnter.py"
        self.Width = 300
        self.Height = 300
        self.Content = XamlReader.Parse(xaml_str)

if __name__ == "__main__":
    win = Window1()
    Application().Run(win)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、Windowの背景をグラデーション表示 《 IMultiValueConverter 使用 》

2011-07-07 01:56:00 | DataBinding
IronPythonで、Windowの背景をグラデーション表示しました。MultiBinding を使って。
Blog: メモ ⇒ [WPF]LinearGradientBrushのGradientStopの色はBindingできない。
http://d.hatena.ne.jp/kn000/20100812/1281632098
を参考にしました。C# から IronPython へ変換しました。
色指定は、Colorの名前だけでなく、16進数でも入力できます。

Lineargradientvalueconverter_2

#
# LinearGradientValueConverter.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase') # for Point
from System import Object
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application, PropertyPath, Point
from System.Windows.Controls import TextBox
from System.Windows.Media import(
        Color,ColorConverter,LinearGradientBrush,GradientStop,Brushes )
from System.Windows.Data import( 
        Binding,BindingOperations, MultiBinding, IMultiValueConverter )

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="LinearGradientValueConverter" Height="300" Width="320">
    <Canvas>  <!-- Text="#FFFFFFFF" or "White"  "#FF000000" or "Black" -->
        <TextBox x:Name="textBox1" Width ="80" Text="#FFFFFFFF" 
                 Canvas.Top = "5" Canvas.Left="8" />
        <TextBox x:Name="textBox2" Width ="80" Text="Black" 
                 Canvas.Top = "25" Canvas.Left="8" />
    </Canvas>
</Window>
"""
class LinearGradientValueConverter(IMultiValueConverter):
    def Convert(self, values, targetType, parameter, culture):
        try:
            color1 = ColorConverter.ConvertFromString(values[0])
            color2 = ColorConverter.ConvertFromString(values[1])
            brush = LinearGradientBrush(StartPoint=Point(0.5, 0.0),EndPoint=Point(0.5, 1.0))
            brush.GradientStops.Add( GradientStop(color1, 0.0) )
            brush.GradientStops.Add( GradientStop(color2, 1.0) )
            result = brush
        except:
            return None
        return result
    def ConvertBack(self, value, targetTypes, parameter, culture):
        return None

class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
        self.textBox1 = win.FindName("textBox1")
        self.textBox2 = win.FindName("textBox2")
        binding = MultiBinding()
        binding.Bindings.Add( Binding(Source = self.textBox1,
                                      Path = PropertyPath(TextBox.TextProperty.Name) ) )
        binding.Bindings.Add( Binding(Source = self.textBox2,
                                      Path = PropertyPath(TextBox.TextProperty.Name) ) )
        binding.Converter = LinearGradientValueConverter()
        #BindingOperations.SetBinding(win, win.BackgroundProperty, binding)
        win.SetBinding(win.BackgroundProperty, binding)

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)


IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、XAMLから、ドックパネル( DockPanel )を表示

2011-07-06 17:11:52 | IronPython
今回は、シンプルなプログラムです。
IronPythonで、XAMLを使って、DockPanelを表示します。
普通のXAMLと、LastChildFill="False" を指定したXAMLです。

Blog: .NETな日々 ⇒ [WPF] WPF入門 ~レイアウト [DockPanel]~
http://blogs.wankuma.com/kzt/archive/2009/03/17/169777.aspx
を、参考にさせていただきました。[ .NETな日々 ]は良くできています。
サンプルが上手に使われていて、わかりやすいです。

#
# DockPanelTestFill.py

import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System import Object
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader
xaml_str="""
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="300" Width="300"> 
    <DockPanel> 
        <Button DockPanel.Dock="Left">Left</Button> 
        <Button DockPanel.Dock="Top">Top</Button> 
        <Button DockPanel.Dock="Right">Right</Button> 
        <Button DockPanel.Dock="Bottom">Bottom</Button> 
        <Button DockPanel.Dock="Top">Fill</Button> 
    </DockPanel> 
</Window>
"""
class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

#
# DockPanelTestNotFill.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System import Object
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader
xaml_str="""
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="300" Width="300"> 
    <DockPanel LastChildFill="False" > 
        <Button DockPanel.Dock="Left">Left</Button> 
        <Button DockPanel.Dock="Top">Top</Button> 
        <Button DockPanel.Dock="Right">Right</Button> 
        <Button DockPanel.Dock="Bottom">Bottom</Button> 
        <Button DockPanel.Dock="Top">Not Fill</Button> 
    </DockPanel> 
</Window>
"""
class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、図形とブラシ( Shape, Brush )を動的に作成

2011-07-05 13:09:30 | IronPython
タブ・コントロール TabControl に、図形・ブラシを動的に作成
BLOG: 続・ひよ子のきもち
2008-10-13 第4章 ブラシ 1/5, LinearGradientBrush
http://d.hatena.ne.jp/kotsubu-chan/20081013
2008-05-12 第2章 TabControl 1/1
http://d.hatena.ne.jp/kotsubu-chan/20080512
等複数のページから、 XAMLとIronPythonのコード を myBlog 用に少しアレンジしています。

続・ひよ子のきもち は、本当に興味深いPageです。
WPF・IronPython・OOP について、色々と教えてもらいました。

Exbrush

#
# exBrush.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase') # for Point, Rect

from System import Object, Uri, UriKind
from System.Windows.Markup import XamlReader
from System.Windows import (
        Window, Application, Point, Rect, LogicalTreeHelper, Thickness)
#from System.Windows.Controls import Canvas
from System.Windows.Media import (
        Color, Colors, SolidColorBrush, Brushes, PointCollection, DrawingGroup, DrawingBrush, 
        VisualBrush, ImageBrush, LinearGradientBrush, RadialGradientBrush, GradientStop,
        GeometryGroup, RectangleGeometry,TileMode,EllipseGeometry, GeometryDrawing)
from System.Windows.Media.Imaging import BitmapImage
from System.Windows.Shapes import Ellipse, Polygon

xaml_str="""
<TabControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <TabItem   Header="SolidColorBrush">
        <WrapPanel Name="solidColorBrush" />
    </TabItem>
    <TabItem   Header="LinearGradientBrush">
        <WrapPanel Name="linearGradientBrush" />
    </TabItem>
    <TabItem   Header="RadialGradientBrush">
        <WrapPanel Name="radialGradientBrush" />
    </TabItem>
    <TabItem   Header="ImageBrush">
        <WrapPanel Name="imageBrush" />
    </TabItem>
    <TabItem   Header="DrawingBrush">
        <WrapPanel Name="drawingBrush" />
    </TabItem>
    <TabItem   Header="VisualBrush">
        <WrapPanel Name="visualBrush" />
    </TabItem>
</TabControl>
"""
class ExWindow(Window):
    def __init__(self, Content=None, **args):
        for key,value in args.items():
            setattr(self,key,value)
        self.InitializeComponent(Content)
        self.init()

    def InitializeComponent(self, Content):
        self.Content = XamlReader.Parse(Content)
        
    def init(self):
        target = (
            "solidColorBrush",
            "linearGradientBrush",
            "radialGradientBrush",
            "imageBrush",
            "drawingBrush",
            "visualBrush",
            )
        self._Controls(target)

    def _Controls(self, target):
        for e in target:
            #c = LogicalTreeHelper.FindLogicalNode(self.Content, e)
            c = self.Content.FindName(e)
            setattr(self, e, c)
        for e in target:
            items = getattr(self, e)
            for shape in self.newEllipse(), self.newPolygon():
                shape.Fill = getattr(self, "_%s"%e)()
                items.Children.Add(shape)

    def _solidColorBrush(self):
        return Brushes.Yellow

    def _linearGradientBrush(self):
        brush = LinearGradientBrush()
        for color, offset in [
            ("Yellow", 0.0),    # follow me ..)^.^)
            ("Green" , 1.0),
            ]: 
            brush.GradientStops.Add(GradientStop(
                Color=getattr(Colors, color),
                Offset=offset,
                ))
        return brush

    def _radialGradientBrush(self):
        brush = RadialGradientBrush()
        for color, offset in [
            ("Yellow", 0.0),    # follow me ..)^.^)
            ("Green" , 1.0),
            ]: 
            brush.GradientStops.Add(GradientStop(
                Color=getattr(Colors, color),
                Offset=offset,
                ))
        return brush

    def _imageBrush(self):
        return ImageBrush(
            ImageSource = BitmapImage(Uri("http://softgarden.lovepop.jp/myBlog/image/j0182772.jpg")))
            #ImageSource= BitmapImage(Uri("j0182772.jpg", UriKind.Relative)))
    def _drawingBrush(self):
        brush = DrawingBrush(
            Viewport=Rect(0, 0, 0.1, 0.1),
            TileMode=TileMode.Tile,
            )
        sheet = GeometryDrawing(
            brush=Brushes.Yellow,
            pen=None,
            geometry=RectangleGeometry(Rect(0, 0, 50, 50)))
        geometry = GeometryGroup()
        for (px, py), rx, ry in (
            ((10, 10), 10, 10),
            ((35, 35), 15, 15),
            ):
            geometry.Children.Add(EllipseGeometry(
                Center=Point(px, py),
                RadiusX=rx,
                RadiusY=ry,
                ))
        marble = GeometryDrawing(
            brush=Brushes.Blue,
            pen=None,
            geometry=geometry)
        drawing = DrawingGroup()
        for e in sheet, marble:
            drawing.Children.Add(e)
        brush.Drawing = drawing
        return brush

    def _visualBrush(self):
        brush = VisualBrush()
        brush.Visual = self.imageBrush
        return brush

    def newEllipse(self):
        return Ellipse(
            Stroke=Brushes.Blue,
            StrokeThickness=2,
            Width=100,
            Height=50,
            )

    def newPolygon(self):
        points = PointCollection()
        vertices = "0,28 80,28 12,80 40,0 68,80"
        for e in vertices.split(" "):
            x, y = eval(e)
            points.Add(Point(x, y))
        return Polygon(
            Stroke=Brushes.Blue,
            StrokeThickness=2,
            Points=points,
            )

if __name__ == "__main__":
    win = ExWindow(Title="exBrush.py", Width=400, Height=200, Content=xaml_str)
    Application().Run(win)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社