Lexa

WPF, C#, Objective C and a little Math

Transform Bitmap in WPF

Sometimes Effects are not enough when you need to modify an image  – in example to highlight it.

Originally the task was to higlight an image (wich might have alpha channel) with different colors – red, green, blue, etc., depending on the state of the application. Googling didnt help a lot, thats why I finished with writing my own (rather plain) function which transforms image content.

This is the function in form of extension:

public static class BitmapSourceExtension
{
    public static BitmapSource HighlightedBitmap(this BitmapSource bitmapSource, Color color)
    {
        if (bitmapSource.Format.BitsPerPixel != 32)
        {
            if (bitmapSource.Format != System.Windows.Media.PixelFormats.Bgra32)
            {
                bitmapSource = new FormatConvertedBitmap(bitmapSource, 
                              System.Windows.Media.PixelFormats.Bgra32, null, 0);
            }
        }

        WriteableBitmap writeableBitmap = new WriteableBitmap(bitmapSource);

        int width = writeableBitmap.PixelWidth;
        int height = writeableBitmap.PixelHeight;

        float cr = ((float)color.R) / 255;
        float cg = ((float)color.G) / 255;
        float cb = ((float)color.B) / 255;
        float ca = ((float)color.A) / 255;

        writeableBitmap.Lock();

        unsafe
        {
            // Get a pointer to the back buffer.
            int pBackBuffer = (int)writeableBitmap.BackBuffer;

            for (int i = 0; i < width * height; ++i, pBackBuffer += 4)
            {
                // Find the address of the pixel to draw.
                uint ucolor = *((uint*)pBackBuffer);

                // Compute the pixel's color.
                uint a = (ucolor >> 24);
                uint r = (ucolor >> 16) & 0xff;
                uint g = (ucolor >> 8 ) & 0xff;
                uint b = (ucolor) & 0xff;

                ucolor =
                    ((uint)(a * ca) << 24) |
                    ((uint)(r * cr) << 16) |
                    ((uint)(g * cg) << 8 ) |
                    ((uint)(b * cb));

                // Assign the color data back to the pixel.
                *((uint*)pBackBuffer) = ucolor;
            }
        }

        // Specify the area of the bitmap that changed.
        writeableBitmap.AddDirtyRect(new System.Windows.Int32Rect(0, 0, width, height));

        // Release the back buffer and make it available for display.
        writeableBitmap.Unlock();

        return writeableBitmap;
    }
}

And this is an example of the Converter which uses the extension:

public class HighlightImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
                          object parameter, System.Globalization.CultureInfo culture)
    {
        if (parameter == null || (value as BitmapSource) == null)
        {
            return value;
        }
        else
        {
            Color color = Colors.White;
            if (value.GetType() == typeof(Color))
            {
                color = (Color)parameter;
            }
            else
            {
                color = (Color)ColorConverter.ConvertFromString(parameter.ToString());
            }
            return ((BitmapSource)value).HighlightedBitmap(color);
        }
    }

    public object ConvertBack(object value, Type targetType, 
                              object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And this is the part of a xaml which generates the result shown above:

<Image Source="robot.jpg" Name="originalImage"/>
<Image Grid.Column="1"
    Source="{Binding Source, 
    ElementName=originalImage,
    Converter={StaticResource HighlightImageConverter},
    ConverterParameter=Orange}" 
    />

UIDatePicker / UIPickerView gradients and the structure

I wanted to implement my own iOS control which should look similar to UIPickers. And of course, I was really interested in the way how these controls are implemented. At least, which windows are composed together to create such a brilliant experience. It was also interesting to learn how gradients are used there. Meanwhile I found this article: http://aralbalkan.com/2985, but the actions described there I found too complicated.

Then I got the idea that I can just simply go through picker subviews and try to hide/show them programmatically. And this worked – now I can see how picker is composed! Moreover, I can render selected view in an image and send it using e-mail for gradient analysis:

 

To create this App, I started with simple UIView based application, and put all needed controls on top of the main view: UIDatePicker, UIImageView, UISlider and UIButton.

Then I added outlets for all controls in the header:

@property (retain, nonatomic) IBOutlet UIDatePicker *picker;
@property (retain, nonatomic) IBOutlet UISlider *slider;
@property (retain, nonatomic) IBOutlet UIImageView *imageView;

- (IBAction) sliderChanged:(id) sender;

When view (and the picker) are completely loaded, its time to initialize slider:

- (UIView*)pickerSubs {
    return [picker.subviews objectAtIndex:0];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    slider.minimumValue = 0;
    slider.maximumValue = [self pickerSubs].subviews.count;
    slider.value = 0;

    previousSelection = 0;
}

When slider value is changed, the next selected window disappears:

-(IBAction) sliderChanged:(id) sender {
    if (previousSelection > 0) {
        // Show subview.
        ((UIView *)[[self pickerSubs].subviews
                    objectAtIndex:previousSelection - 1]).hidden = NO;

        imageView.image = nil;
    }

    previousSelection = (int)slider.value;

    if (previousSelection > 0)
    {
        // Render subview.
        UIView *subview = (UIView *)[[self pickerSubs].subviews
                                     objectAtIndex:previousSelection - 1];

        UIGraphicsBeginImageContext(subview.bounds.size);
        [subview.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        imageView.image = resultingImage;

        // Hide subview.
        subview.hidden = YES;
    }
}

Simple solution, a lot of interesting info as a result. Nice work, Apple!

 


Fast L-System rendering with OpenGL

Main news: WPF 3d renderer in the Viewer is replaced with OpenGL renderer (using OpenTK library). Now rendering is really fast. I didn’t do anything special: when L-System symbols string is parsed, all elements are collected in a huge array of vertexes, colors and normals, which is then rendered using glDrawArrays function.

The other interesting feature is “smooth” path of a turtle. Before each turtle movement was represented with a box, so sequence of movements looked like a chain of boxes. Now turtle path looks like a pipe, and user is allowed to change number of edges of the pipe. Below is an example of curly L-System with “smooth” rendering. Old way of rendering is still available though.

 

The other changes are related to StringParser, which helps to transform character strings to list of symbol objects. Now it support parameters in brackets. If parameters are present, then StringParser uses parameters as an array of doubles, and create a symbol using its constructor with double parameters. The source code of a Spiral above uses this feature in its production functions:

public class Spiral : LSystems.Turtle.SystemDefinition, LSystems.IRewriteRules
{
    public class e
    {
        public int Index { get; set; }
        public e() { this.Index = 0; }
        public e(double index) { this.Index = (int)index; }
    };

    public class s
    {
        public int Index { get; set; }
        public s() { this.Index = 0; }
        public s(double index) { this.Index = (int)index; }
    };

    public class D { };

    private LSystems.Turtle.StringParser parser = new LSystems.Turtle.StringParser();

    public Spiral()
    {
        parser.Register(typeof(e));
        parser.Register(typeof(s));
        parser.Register(typeof(D));
    }

    private const int GrowIndex = 8;

    [LSystems.Production]
    public object Grow(e endpoint)
    {
        int index = (endpoint.Index + 1) % GrowIndex;
        return parser.Produce(string.Format(
            "^+DF{0}e({1})",
            (index == 0 ? "[Ds]" : ""),
            index));
    }

    [LSystems.Production]
    public object Grow(s endpoint)
    {
        int index = (endpoint.Index + 1) % GrowIndex;
        return parser.Produce(string.Format(
            "-&DF{0}s({1})",
            (index == 0 ? "[De]" : ""),
                index));
    }

    [LSystems.Turtle.Interpret]
    public void Smaller(D d)
    {
        Turtle.SetColor(1, 1.0 - Turtle.Distance / 100.0, 0);
        Turtle.Distance = Turtle.Distance * 0.95;
        Turtle.Thickness = Turtle.Thickness * 0.93;
    }

    public object Axiom
    {
        get { return parser.Produce("#(100)d(100)a(45)\\a(20)e"); }
    }

    public int Depth
    {
        get { return 80; }
    }

    public LSystems.RewriteDirection RewriteDirection
    {
        get { return LSystems.RewriteDirection.LeftToRight; }
    }
}

Executable  Release.04 is here: http://tatalata.com/Blog/Viewer.Release.04.zip

Updated source code is already in the repository.


Some UI changes and Code editor

Some UI changes have been done to LSystems Viewer:
– a button to generate next step of L-System.
– a button to rebuild system (makes sense for stochastic L-Systems).
– improved mouse behavior in 3d view.

The AvalonEdit control (created by Daniel Grunwald, check this article on codeproject) is used as internal editor for opened L-System source code file. Every time when editing is saved, Viewer compiles the file and rebuilds the system, if compilation succeeded.

Updated source code is already in the repository.
And here is the link to the binary version: Viewer.Release.03.zip


Bush!

Todays update: Push command of the Turtle not only pushes position, but also thickness and color, Pop command restores them. And here are some results – improved Flower and Bush (with “realistic” thickness of the stem!):


Flowers with L-System

Today I added filled polygons (called Surfaces) in L-Systems, so now it is possible to define some polygonal stuff, i.e. flowers. Next example is based on flower system from the book (figure 1.26), but with some modifications:

Viewer application was extended – now it is possible to check every build iteration of selected L-System (called steps). So, for the picture above step #3 is selected.

The other new feature is LSystems.Turtle.StringParser class. This is just a helper class, which allows to build modules string from characters string. In case of D0L systems its very convenient to use just simple strings, this was the reason to introduce this class. For example, the following Hilbert 3d Curve:

was generated by the following system using StringParser:

class Hilbert3d : LSystems.Turtle.SystemDefinition, LSystems.IRewriteRules
{
    public class A {}
    public class B {}
    public class C {}
    public class D {}

    private LSystems.Turtle.StringParser parser =
    new LSystems.Turtle.StringParser()
    {
        CharToObject = c =>
        {
            switch (c)
            {
            case 'A': return new A();
            case 'B': return new B();
            case 'C': return new C();
            case 'D': return new D();
            default: return null;
            }
        }
    };

    [LSystems.Production]
    public object Produce(A a)
    {
        return parser.Produce("B-F+CFC+F-D&F^D-F+&&CFC+F+B//");
    }

    [LSystems.Production]
    public object Produce(B a)
    {
        return parser.Produce("A&amp;F^CFB^F^D^^-F-D^|F^B|FC^F^A//");
    }

    [LSystems.Production]
    public object Produce(C c)
    {
        return parser.Produce("|D^|F^B-F+C^F^A&&FA&F^C+F+B^F^D//");
    }

    [LSystems.Production]
    public object Produce(D d)
    {
        return parser.Produce("|CFB-F+B|FA&F^A&&FB-F+B|FC//");
    }

    public object Axiom
    {
        get { return new A(); }
    }
    public int Depth
    {
        get { return 4; }
    }
    public LSystems.RewriteDirection RewriteDirection
    {
        get { return LSystems.RewriteDirection.LeftToRight; }
    }

    // Colors.
    double color = 0;
    double delta = 0.05;

    [LSystems.Turtle.Interpret]
    public void Draw(LSystems.Turtle.F f)
    {
        this.Turtle.SetThicknessAndColor(33, 1, color, 0);
        this.Turtle.Forward(100, true);

        color += delta;
        if (color > 1)
        {
            color = 1;
            delta = -delta;
        }
        else if (color < 0)
        {
            color = 0;
            delta = -delta;
        }
    }
}

StringParser class is able to recognize most basic turtle commands (turns, moves), all custom symbols can be added usingCharToObject function (see example above).

Updated source code can be found in the repository.


The Book


I just received the original “The Algorithmic Beauty of Plants” which I bought for 25 euros on the Amazon. The book is in A4 format and has a hard cover. Its just great to have it, I love books :)


I bought a Mac

So its finally happened.

I had a lot of reasons to do it, and I’m absolutely exited about the result. I have smallest macbook pro and I am happy. This is probably the most interesting and nice experience in computers for me both as user and programmer since many years.

Noticing beautiful Mac UI interface I thought about using the shadow for ModalUserControls from my previous post. It is really easy to do using DropShadowEffect, here is modified control template (see Effect node after comment):

<ControlTemplate TargetType="{x:Type ContentControl}">
    <Grid Focusable="False">
        <ContentPresenter Content="{TemplateBinding Content}">
        ...
        </ContentPresenter>
        <ContentPresenter Content="{Binding ...}">
        <!-- Shadow effect for modal content -->
            <ContentPresenter.Effect>
                <DropShadowEffect
                    BlurRadius="20"
                    ShadowDepth="0"
                    Color="Gray"/>
            </ContentPresenter.Effect>
        </ContentPresenter>
    </Grid>
</ControlTemplate>

And this is how it looks:

Much better, isn’t it?

I’m going to continue develop stuff in Windows/C#/WPF, but someday Objective-C will arrive on this page 😉


Modal UserControl in WPF

Common approach to show some modal view (dialog) in WPF application is to use some kind of “IModalDialogService” realization which creates a window on View side and places View corresponding to requested ViewModel inside it.

There is also the other way – just to put a control element above the current main window content. This article is about this approach.

MVVM is going to be used in the following manner:
– There are some ViewModel types that represent windows (or pages or similar objects) in the application.
– These types have some property (i.e.”ModalContent”) of type object.
– If ModalContent property is not null, its content shall be shown with some View over the parent ViewModels View.

As example, I create WPF application project and add to main window the described above ModalContent property and 2 handlers – to set and unset it (this is the very first test, so I will not use ViewModel – MainWindow will be View and ViewModel at the same time, oops):

public partial class MainWindow : Window
{
    public object ModalContent
    {
        get { return (object)GetValue(ModalContentProperty); }
        set { SetValue(ModalContentProperty, value); }
    }

    public static readonly
        DependencyProperty ModalContentProperty =
            DependencyProperty.Register(
            "ModalContent",
            typeof(object),
            typeof(MainWindow),
            new UIPropertyMetadata(null));

    private void ShowModalClick(object sender, RoutedEventArgs e)
    {
        this.ModalContent = new ModalContent();
    }

    private void HideModalClick(object sender, RoutedEventArgs e)
    {
        this.ModalContent = null;
    }
}

ModalContent class is contains only one property – Text:

public class ModalContent
{
    public ModalContent()
    {
        this.Text = "Current time is " + DateTime.Now.
    }
    public string Text { get; set; }
}

We need to configure xaml, initial layout rool will represent a window with a button. Button will show modal content when user presses it:

<Grid>
  <Button
    Click="ShowModalClick"
    Content="ShowModal"
    VerticalAlignment="Top"/>
</Grid>

Control, representing modal control shall be above the button. I will use ContentPresenter and connect it to ModalContent property:

<Grid>
  <Button
    Click="ShowModalClick"
    Content="ShowModal"
    VerticalAlignment="Top"/>

  <ContentPresenter Content="{Binding ModalContent}">
    <ContentPresenter.Resources>
    <DataTemplate DataType="{x:Type Source:ModalContent}">
      <Border
        Background="LightGreen"
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Padding="30"
        CornerRadius="5">
        <StackPanel>
          <TextBlock Text="{Binding Text}"/>
          <Button Click="HideModalClick">
            Hide Modal
          </Button>
        </StackPanel>
      </Border>
    </DataTemplate>
    </ContentPresenter.Resources>
  </ContentPresenter>
</Grid>

 

Now, when button is “ShowModal” is pressed, we have a UserControl on top.

Problem is that it is not completely modal – we still can press “underlying” “ShowModal” button. Luckily, it is easy to fix using by setting IsEnabled property:

<Button
  Click="ShowModalClick"
  Content="ShowModal"
  VerticalAlignment="Top">
  <Button.Style>
    <Style TargetType="{x:Type Button}">
      <Setter Property="IsEnabled" Value="false" />
        <Style.Triggers>
          <DataTrigger
            Binding="{Binding ModalContent}"
            Value="{x:Null}">
            <Setter Property="IsEnabled" Value="True"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>
  </Button.Style>
</Button>

Its working as expected now. For user it is also clearer that underlying view cannot be used – it is “gray”.

The project is called SimpleModalUserControl and can be found at the end of the article.

Next and final example is a bit more complex. I defined new ViewModel base class called ModalHostViewModel, which contains ModalContent property. ModalHostViewModel can also play a role of modal content, thats why it also has ModalParent property referencing it.

To present content of ModalHostViewModel in a View, I used ContentControl with custom style. The modal ViewModel object shall be binded to ContentControl Tag property and when it becomes valid (not null), it displayed over content of ContentControl as modal element using ContentPresenter (so DataTemplate for ModalContent shall be defined somewhere in resources). Sound a bit tricky, so look at example of the usage:

<ContentControl
  Tag="{Binding ModalChild}"
  Style="{StaticResource ModalHostControlStyle}">

  <!-- here goes content of the window, which will be
  disabled when ModalChild will become valid -->

</ContentControl>

 

The custom ContentControl Style applies the following template to ContentControl:

<ControlTemplate TargetType="{x:Type ContentControl}">
  <Grid Focusable="False">
  <ContentPresenter Content="{TemplateBinding Content}">
    <ContentPresenter.Style>
      <Style TargetType="{x:Type ContentPresenter}">
        <Setter Property="IsEnabled" Value="false"/>
        <Style.Triggers>
          <DataTrigger
            Binding="{Binding Tag, RelativeSource={RelativeSource
              AncestorType={x:Type ContentControl}}}"
            Value="{x:Null}">
          <Setter Property="IsEnabled" Value="True"/>
          </DataTrigger>
        </Style.Triggers>
      </Style>
    </ContentPresenter.Style>
    </ContentPresenter>
    <ContentPresenter
        Content="{Binding Tag, RelativeSource={RelativeSource 
            AncestorType={x:Type ContentControl}}}"/>
  </Grid>
</ControlTemplate>

So, complex demo contains a list of .Net default colors.

If user performs double click on color record, the application shows color modal content (the same “dialog” will be called if user presses enter key).

If user presses “SayHello” button, the other modal content is placed on top of it.

The last issue which I came across during implementation – incorrect behavior of the keyboard focus. The focus was not restored to the correct element when modal view was “closed”. The solution which I found – is to memorize focused element of the view become disabled, and restore the focus when it is enabled again. It is implemented using attached properties, and used in described above ContentControl Style. See attached solution for details.

Complete vs 2008 solution can be found here.


Cutting module in LSystems

Cutting is now in the library. It is used to simulate shedding of plant parts, i.e. palm trees. The idea of shedding is the following: if cut symbol (module) is in the string, then all following symbols in current branch are skipped, i.e.

R, StartBranch, F, Cut, F, L, EndBranch

is transformed into

R, StartBranch, F, EndBranch

At the moment shedding itself (applying cut modules to the string) is done in Decomposite method, so no additional special functions were added to the System class.

An example of system using shedding is added to Viewer assembly.
Updated source code is already in the repository.