« Previous : 1 : 2 : 3 : 4 : 5 : ... 6 : Next »

참조 : http://blogs.msdn.com/llobo/archive/200 ··· ing.aspx

만약 여러분이 실버라이트에 익숙하다면 새로운 것은 없습니다. 이 속성 FrameworkElement에 새로이 추가가 되었었는데 각 길이를 반올림 하는 기능입니다. 기본 값은 실버라이트와 다르게 False이며 값을 설정하게 되면 자식 요소에 상속 됩니다. 이 속성을 설정한 것과 설정하지 않은 것은 다음과 같이 차이를 볼 수 있습니다.

사용자 삽입 이미지

예제 코드는 다음과 같습니다.

사용자 삽입 이미지

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/12/30 17:25 2009/12/30 17:25
Posted by 나는산.
TAGS

Leave your greetings here.

[로그인][오픈아이디란?]
참조 : http://blogs.msdn.com/llobo/archive/200 ··· ogs.aspx

기존 OpenFileDialog나 SaveFileDialog가 XP 스타일 이였던 것을 Windows Vista/7 스타일로 수정되었습니다.

기존에는 다음과 같았으나,

사용자 삽입 이미지
다음과 같이 변경되었습니다.

사용자 삽입 이미지



크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/12/30 16:02 2009/12/30 16:02
Posted by 나는산.
TAGS

Leave your greetings here.

[로그인][오픈아이디란?]

참조 : http://blogs.msdn.com/llobo/archive/200 ··· ons.aspx

Easing 함수들은 여러분들의 애니메이션들에 사용자 정의 수학 방정식들을 추가할 수 있게 해줍니다. 이런 사용자 정의 수학 방정식들을 이용하면 애니매이션들은 더 실제와 같거나 부드럽습니다. WPF 4에서는 이런 사용자 정의 수학 방정식 11개가 미리 정의 되어 있습니다. 이들 각 함수들은 3개의 모드(EaseIn, EaseOut, EaseInOut)를 가집니다.

이번 WPF 4에서 기존에 있었거나 새롭게 추가된 애니매이션 관련 클래스들 - ByteAnimation, ColorAnimation, DecimalAnimation, DoubleAnimation, Int16Animation, Int32Animation, Int64Animation, Point3DAnimation, PointAnimation, QuaternionAnimation, RectAnimation, Rotation3DAnimation, SingleAnimation, SizeAnimation, ThicknessAnimation, Vector3DAnimation, VectorAnimation 등 - 전반적으로 EasingFunction 속성이 추가되었다. 이 속성은 IEasingFunction이라는 인터페이스로 정의 되어 있으며, 이것은 개발자에게 다양한 효과를 애니메이션에 적용할 수 있도록 만들수 있도록 해줍니다.

IEasingFunction에 대해서 더 자세하게 얘기하자면 0과 1사이의 정규화된 시간에 각각 값을 반환할 수 있는 함수를 만들 수 있도록 해준다. 쉽게 얘기하면 0은 애니메이션이 시작하는 값이고 1은 애니메이션이 끝나는 값을 가리킵니다.

WPF 4에서는 IEasingFunction을 상속받아 미리 정의해놓은 클래스가 11개가 있다고 했습니다. 이들은 클래스는 공통적으로 System.Windows.Media.Animation.EasingFunctionBase 클래스를 상속합니다. 대부분 미리 정의해 놓은 EasingFunction을 사용하지 않고 사용자가 직접 개발한다면 이 클래스를 상속 받아 사용합니다. EaseInCore 함수를 오버라이드 하여 작성하면 되는데 다음과 같이 하면 됩니다.

namespace CustomEasingFunction
{
    public class CustomSeventhPowerEasingFunction : EasingFunctionBase
    {
        public CustomSeventhPowerEasingFunction()
            : base()
        {
        }

        // Specify your own logic for the easing function by overriding

        // the EaseInCore method. Note that this logic applies to the "EaseIn"

        // mode of interpolation. 

        protected override double EaseInCore(double normalizedTime)
        {
            // applies the formula of time to the seventh power.

            return Math.Pow(normalizedTime, 7);
        }

        // Typical implementation of CreateInstanceCore

        protected override Freezable CreateInstanceCore()
        {

            return new CustomSeventhPowerEasingFunction();
        }

    }
}

EasingFunctionBase는 EasingMode 속성을 가지고 있습니다. EasingMode는 다음과 같이 3가지 모드가 있습니다.
- EaseIn : 기본 EaseInCore 구현대로 작동됩니다.
- EaseOut : 기본 EaseInCore와 반대로 작동됩니다. (X, Y좌표 -1 곱한값)
- EaseInOut : EaseIn 실행후 EaseOut 실행됩니다.

미리 정의해놓은 EasingFunction은 다음과 같습니다.

사용자 삽입 이미지

사용자 삽입 이미지

사용자 삽입 이미지

결론적으로 어떻게 보면 기존 Spline 사용하는 것을 더 넓게 적용, 더 자세하게 제어할 수 있게 되었다고 생각하면 될 것 같습니다.
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/12/30 15:40 2009/12/30 15:40
Posted by 나는산.
TAGS

Leave your greetings here.

[로그인][오픈아이디란?]

참조 : http://blogs.msdn.com/llobo/archive/200 ··· ush.aspx

WPF 4 부터는 TextBoxBase를 상속 받는 RichTextBox와 TextBox 컨트롤와 PasswordBox 컨트롤에 새로운 속성인 CaretBrush, SelectionBrush 그리고 SelectionOpacity가 추가되었다.

이전 버전에서는 텍스트 선택 색상과 투명도를 조절할 수 없었으며, 현재 커서 색상을 수정할 수 없었습니다. WPF4 부터는 텍스트 선택 부분을 개발자가 Brush로 설정하거나 텍스트 선택 부분의 투명도를 설정할 수 있습니다. 또, 현재 커서도 개발자가 Brush로 설정할 수 있습니다.

CaretBrush는 현재 커서의 표시를 Brush로 설정하거나 가져옵니다.
SelectionBrush는 현재 선택 부분의 표시를 Brush로 설정하거나 가져옵니다.
SelectionOpacity는 현재 선택 부분의 표시의 투명도를 설정하거나 가져옵니다.

사용자 삽입 이미지

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/12/30 14:47 2009/12/30 14:47
Posted by 나는산.
TAGS

Leave your greetings here.

[로그인][오픈아이디란?]
When we want to declaratively use our custom controls or reference the types we defined in XAML, we should declare the XML namespace to map to the CLR namespace in which the controls and types are defined as the following XAML snippt demonstrates:

<Page x:Class="Test.MainWindow"
         xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
         xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:cc
="clr-namespace:Sheva.Windows.Controls;assembly=AvalonLib"
/>

    Recently, I am heavily engaged with writing a resuable WPF control library, and quite often I need to create some pages to test those controls I create, so ever now and then I have to use the cumbersome syntax like above to declare the XML namespace, personally I don't like the syntax, and I thought Microsoft WPF team should come up with a more elegant way of doing it, and in actuality, they did introduce an alternative to do it since the CTP releases. there is a custom attribute called XmlnsDefinitionAttribute in the System.Windows.Markup namespace which allows you to apply to the assembly which contains the types and controls the XAML code would reference.the built-in WPF assemblies such as WindowsBase.dll, PresentationCore.dll, and PresentationFramework.dll all have this attribute applied, and all have http://schemas.microsoft.com/winfx/2006/xaml/presentation namespace mapped with the CLR namespaces introduced by them. and of cause you can use this attribute in your own project, just open the AssemblyInfo.cs file, and append the following directive:

[assembly: XmlnsDefinition("http://schemas.sheva.com/wpf/", "Sheva.Windows.Controls")]

    Then you can declare the namespace alias in XAML this way:

<Page x:Class="Test.MainWindow"
         xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
         xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:cc
="http://schemas.sheva.com/wpf/"
/>
   
    Wow, this is a bit like the built-in xmlns declaration indeed, really really cool indeed:)
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/11/25 12:15 2009/11/25 12:15
Posted by 나는산.
TAGS

Leave your greetings here.

[로그인][오픈아이디란?]
public enum SampleEnum
{
Dog,
Cat,
Scrat,
Hefalump
}

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApplication1"
Title="Bind to Enum" Height="250" Width="250">
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum"
MethodName="GetValues" ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:SampleEnum"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
Margin="10,10,10,0" Height="80" VerticalAlignment="Top" />
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
Margin="10,0,10,80" Height="25" VerticalAlignment="Bottom" />
</Grid>
</Window>
크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/11/24 16:49 2009/11/24 16:49
Posted by 나는산.

Leave your greetings here.

[로그인][오픈아이디란?]
WPF에서 Animation을 사용하면 CPU 사용률이 올라간다.

기본적으로 WPF에서 Animation은 60 Frame이 유지 되도록 설정되어 있다.

변경하려면 다음과 같이 Frame을 내리면 된다.

   1: Timeline.DesiredFrameRateProperty.OverrideMetadata(
   2:             typeof(Timeline),
   3:             new FrameworkPropertyMetadata { DefaultValue = 20 }
   4:             );

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/09/09 20:31 2009/09/09 20:31
Posted by 나는산.

Leave your greetings here.

[로그인][오픈아이디란?]


흔히 WPF를 사용하다보면, WinForm에 있는 System.Drawing.Bitmap을 가져와 사용할때가 있는다.

그래서 흔시 Googling을 하다보면 다음 코드를 사용하게 된다.

        public static BitmapSource ConvertToBitmapSource(System.Drawing.Bitmap source)

        {

            var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(

                source.GetHbitmap(),

                IntPtr.Zero,

                Int32Rect.Empty,

                BitmapSizeOptions.FromEmptyOptions());

            bitmapSource.Freeze();


            return bitmapSource;

        }



그런데 이 코드는 메모리 문제가 있는다. 계속 호출하면 메모리가 증가한다.

ㅠ.ㅠ

다시 자세히 검사해보면 다음 코드를 발견할 수 있다.

        private static BitmapSource CreateBitmapSource(Bitmap bitmap)

        {

            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);


            BitmapSource source = BitmapSource.Create(bitmap.Width, bitmap.Height,

                bitmap.HorizontalResolution, bitmap.VerticalResolution, PixelFormats.Pbgra32, null,

                bitmapData.Scan0, bitmapData.Stride * bitmap.Height, bitmapData.Stride);


            bitmap.UnlockBits(bitmapData);


            return source;

        }



일단 많이 호출해도 메모리가 증가하지 않는다.

그럼 위에 코드는 뭐가 잘못 되었을까?


source.GetHbitmap() 부분이 문제라고 한다.


핸들을 갔다가 사용했으면 반환해야 한다.


다음과 같이 수정하면 메모리 증가가 없다.

        private static readonly List<IntPtr> _bitmapsToDelete = new List<IntPtr>();


        [DllImport("gdi32.dll")]

        private static extern bool DeleteObject(IntPtr hObject);


        private static void DeleteBitmaps()

        {

            foreach (IntPtr bitmap in _bitmapsToDelete)

            {

                DeleteObject(bitmap);

            }

            GC.Collect(0, GCCollectionMode.Forced);

        }


        public static BitmapSource ConvertToBitmapSource(System.Drawing.Bitmap source)

        {

            DeleteBitmaps();


            IntPtr handle = source.GetHbitmap();

            _bitmapsToDelete.Add(handle);


            var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(

                handle,

                IntPtr.Zero,

                Int32Rect.Empty,

                BitmapSizeOptions.FromEmptyOptions());

            bitmapSource.Freeze();


            return bitmapSource;

        }


필자는 전자 방법이 문제가 없었다.

두번째 방법은 UI 쓰레드 때문에 조금 손봤어야 했다.

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/08/31 23:05 2009/08/31 23:05
Posted by 나는산.
TAGS

Leave your greetings here.

[로그인][오픈아이디란?]

public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse)
        {
            foreach (T item in source)
            {
                yield return item;

                IEnumerable<T> seqRecurse = fnRecurse(item);

                if (seqRecurse != null)
                {
                    foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse))
                    {
                        yield return itemRecurse;
                    }
                }
            }
        }

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/07/01 01:27 2009/07/01 01:27
Posted by 나는산.
TAGS ,

Leave your greetings here.

[로그인][오픈아이디란?]

참조 : http://1.11011.net/archives/000698.html

using System.IO;
using System.Windows.Markup;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Build.BuildEngine;

public static class BamlWriter
{
    public static void Save(object obj, Stream stream)    
   {        
        string
path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
        Directory.CreateDirectory(path);

        try
        {
            string xamlFile = Path.Combine(path, "input.xaml");
            string projFile = Path.Combine(path, "project.proj");
           
            using (FileStream fs = File.Create(xamlFile))
            {
                XamlWriter.Save(obj, fs);
            }

            Engine engine = new Engine();
            engine.BinPath = RuntimeEnvironment.GetRuntimeDirectory();
            Project project = engine.CreateNewProject();
            BuildPropertyGroup pgroup = project.AddNewPropertyGroup(false);
            pgroup.AddNewProperty("AssemblyName", "temp");
            pgroup.AddNewProperty("OutputType", "Library");
            pgroup.AddNewProperty("IntermediateOutputPath", ".");
            pgroup.AddNewProperty("MarkupCompilePass1DependsOn", "ResolveReferences");

            BuildItemGroup igroup = project.AddNewItemGroup();
            igroup.AddNewItem("Page", "input.xaml");
            igroup.AddNewItem("Reference", "WindowsBase");
            igroup.AddNewItem("Reference", "PresentationCore");
            igroup.AddNewItem("Reference", "PresentationFramework");

            project.AddNewImport(@"$(MSBuildBinPath)\Microsoft.CSharp.targets", null);
            project.AddNewImport(@"$(MSBuildBinPath)\Microsoft.WinFX.targets", null);
            project.FullFileName = projFile;

            if (engine.BuildProject(project, "MarkupCompilePass1"))
            {
                byte[] buffer = new byte[1024];
                using (FileStream fs = File.OpenRead(Path.Combine(path, "input.baml")))
                {
                    int read = 0;
                    while (0 < (read = fs.Read(buffer, 0, buffer.Length)))
                    {
                        stream.Write(buffer, 0, read);
                    }
                }
            }
            else
            {
                // attach a logger to the Engine if you need better errors
                throw new System.Exception("Baml compilation failed.");
            }
        }
        finally
        {
            Directory.Delete(path, true);
        }
    }
}

public static class BamlReader
{
    public static object Load(Stream stream)
    {
        ParserContext pc = new ParserContext();
        return typeof(XamlReader)
            .GetMethod("LoadBaml", BindingFlags.NonPublic | BindingFlags.Static)
            .Invoke(null, new object[] { stream, pc, null, false });
    }
}

크리에이티브 커먼즈 라이센스
Creative Commons License
이올린에 북마크하기(0) 이올린에 추천하기(0)
2009/05/08 20:38 2009/05/08 20:38
Posted by 나는산.

Leave your greetings here.

[로그인][오픈아이디란?]
« Previous : 1 : 2 : 3 : 4 : 5 : ... 6 : Next »