myBlog

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

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スタートブック
辻 真吾
技術評論社

IronPythonで、ColorListView を作りました

2011-07-05 03:50:48 | DataBinding
カラー・リストビュー ( ColorListView )を作ってみました。
BLOG: 続・ひよ子のきもち ==> ListView
http://d.hatena.ne.jp/kotsubu-chan/20090706
から、XAML と IronPython のコード を myBlog 用に少しアレンジしています。
XAMLのなかで、DataBinding が使われています。

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

Exlistview

#
# exListView.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')
from System import Object
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application
from System.Windows.Media import SolidColorBrush, Brushes
#from System.Windows.Controls import Grid
#from System.Windows.Data import Binding, BindingOperations
from System.Collections.ObjectModel import ObservableCollection

xaml_str="""
<DockPanel LastChildFill="True"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ListView Name="listView" DockPanel.Dock="Left">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Color Name" 
                    DisplayMemberBinding="{Binding Path=name}"  Width="90" />
                <GridViewColumn Header="Red" 
                    DisplayMemberBinding="{Binding Path=red}"   Width="45" />
                <GridViewColumn Header="Green" 
                    DisplayMemberBinding="{Binding Path=green}" Width="45" />
                <GridViewColumn Header="Blue" 
                    DisplayMemberBinding="{Binding Path=blue}"  Width="45" />
            </GridView>
        </ListView.View>
    </ListView>
    <Canvas Name="colorBox" />
</DockPanel>
"""
class ColorItem:
    def __init__(self, name):
        e = getattr(Brushes, name).Color
        self.name  = name
        self.red   = e.R
        self.green = e.G
        self.blue  = e.B
    def __str__(self):
        return "'%s'(%d,%d,%d)"%(
            self.name, self.red, self.green, self.blue)

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 = "listView", "colorBox"
        for e in target:
            control = self.Content.FindName(e)
            setattr(self, e, control)     
        self.listView.ItemsSource = ObservableCollection[Object]()
        for e in self.colorBrushes():
            self.listView.ItemsSource.Add(ColorItem(e))            
        self.listView.SelectionChanged += self.selectionChanged
        
    def colorBrushes(self):
        return [e for e in dir(Brushes)
            if isinstance(getattr(Brushes, e), SolidColorBrush)]
    
    def selectionChanged(self, sender, e):
        e = sender.SelectedItem
        print e
        self.colorBox.Background = getattr(Brushes, e.name)        

if __name__ == "__main__":
    win = ExWindow(Title="exListView", Width=380, Height=150, Content=xaml_str)
    Application().Run(win)


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