Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > .NET Frameworks (точка нет фреймворки) > WPF, UWP, WinRT, XAML
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 04.04.2016, 14:11   #1
ViktorGugo
Новичок
Джуниор
 
Регистрация: 04.04.2016
Сообщений: 4
По умолчанию Объединение объектов в форме WPF

Всем привет! Прошу помощи! Совершенно не имею опыта в WPF, на данный момент не получается объединить объекты: несколько квадратов Rectangle и кривую Безье. Мне надо, чтобы части квадратов, находящиеся выше кривой - не отображались - имели белый цвет.
Во вложении две картинки: как выглядит сейчас картинка и как должна выглядеть.

Вообще мне надо реализовать это в динамическом коде, то есть файле *.cs , но пока пытаюсь хотя бы в разметке это сделать.

Вот разметка:
Код:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Rectangle Width="25" Height="25" Fill="AntiqueWhite" Margin="246,97,246,198" />
        <Rectangle Width="25" Height="25" Fill="Wheat" Margin="221,122,271,173" />
        <Rectangle Width="25" Height="25" Fill="Tomato" Margin="246,97,246,198" />
        <Rectangle Width="25" Height="25" Fill="Red" Margin="196,72,296,223" />
        <Rectangle Width="25" Height="25" Fill="Aqua" Margin="196,97,296,198" />
        <Rectangle Width="25" Height="25" Fill="Green" Margin="271,72,221,223" />
        <Rectangle Width="25" Height="25" Fill="Teal" Margin="246,72,246,223" />
        <Rectangle Width="25" Height="25" Fill="Yellow" Margin="221,72,271,223" />
        <Rectangle Width="25" Height="25" Fill="Olive" Margin="271,122,221,173" />
        <Rectangle Width="25" Height="25" Fill="Black" Margin="246,122,246,173" />
        <Rectangle Width="25" Height="25" Fill="YellowGreen" Margin="196,122,296,173" />
        <Rectangle Width="25" Height="25" Fill="Chocolate" Margin="221,97,271,198" />
        <Rectangle Width="25" Height="25" Fill="Coral" Margin="271,97,221,198" />
        <Path Stroke="Red">
            <Path.Data>
                <PathGeometry>
                    <PathFigure IsClosed="false" StartPoint="196,147">
                        <QuadraticBezierSegment Point1="246,0" Point2="296,147" />
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
        <Path Stroke="Red">
            <Path.Data>
                <PathGeometry>
                    <PathFigure IsClosed="false" StartPoint="196,147">
                        <QuadraticBezierSegment Point1="246,0" Point2="296,147" />
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
    </Grid>
</Window>
Пробовал сделать с помощью CombinedGeometry, но многочасовые попытки не увенчались успехом. Выдает ошибку, что не с теми типами работаю.
Код:
<Window x:Class="PathMarkupDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Path Demo"
        Height="300" Width="300">
    <Window.Resources>
                <Path Stroke="Red" x:Key="fig" >
            <Path.Data>
                <PathGeometry >
                    <PathFigure IsClosed="false" StartPoint="196,147" >
                        <QuadraticBezierSegment Point1="246,0" Point2="296,147" />
                    </PathFigure>
                </PathGeometry>
            </Path.Data>
        </Path>
        <EllipseGeometry x:Key="ellipse" Center="85 50" RadiusX="65" RadiusY="35"></EllipseGeometry>
    </Window.Resources>
    <Path Grid.Row="1"  Stroke="Blue" Margin="5">
        <Path.Data>
            <CombinedGeometry GeometryCombineMode="Intersect"
            CombinedGeometry.Geometry1="{StaticResource fig}"
            CombinedGeometry.Geometry2="{StaticResource ellipse}"
                              >
            </CombinedGeometry>
        </Path.Data>
    </Path>
</Window>
Изображения
Тип файла: png до.png (6.3 Кб, 106 просмотров)
Тип файла: jpg после.jpg (29.2 Кб, 102 просмотров)
ViktorGugo вне форума Ответить с цитированием
Старый 04.04.2016, 14:13   #2
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Какую именно ошибку?
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 04.04.2016, 14:22   #3
ViktorGugo
Новичок
Джуниор
 
Регистрация: 04.04.2016
Сообщений: 4
По умолчанию Ошибка

Не удается применить объект типа "System.Windows.Shapes.Path" к свойству, для которого требуется тип "System.Windows.Media.Geometry" .
ViktorGugo вне форума Ответить с цитированием
Старый 04.04.2016, 14:32   #4
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Туда наверно надо PathGeometry, а не Path.
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 04.04.2016, 14:40   #5
ViktorGugo
Новичок
Джуниор
 
Регистрация: 04.04.2016
Сообщений: 4
По умолчанию

Вообще, во втором листинге я попытался объединить только один эллипс с кривой и их я объявляю в Window.Resources
Может, не лучший способ - делать комбинирование через CombinedGeometry.
Дело в том, что цвета квадратов и их координаты я не знаю заранее, и их большое множество.
ViktorGugo вне форума Ответить с цитированием
Старый 04.04.2016, 16:49   #6
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Так задача-то в чем? Откуда берутся квадраты и кривая?

Простой пример с одним прямоугольником как-то так:
Код:
<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="525">
    <Window.Resources>
        <PathGeometry x:Key="fig" >
            <PathFigure IsClosed="false" StartPoint="-10,180" >
                <QuadraticBezierSegment Point1="80,0" Point2="215,180" />
            </PathFigure>
        </PathGeometry>
        <RectangleGeometry x:Key="rect" Rect="0,30,200,150"></RectangleGeometry>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Path Grid.Row="0" Margin="25" Fill="Orange" Data="{StaticResource rect}" />

        <Path Grid.Row="0" Margin="25" Stroke="Blue" Data="{StaticResource fig}" />

        <Path Grid.Row="1" Margin="25" HorizontalAlignment="Center" Fill="Orange">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Intersect"
                    Geometry1="{StaticResource rect}"
                    Geometry2="{StaticResource fig}">
                </CombinedGeometry>
            </Path.Data>
        </Path>
    </Grid>
</Window>
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Старый 04.04.2016, 19:48   #7
ViktorGugo
Новичок
Джуниор
 
Регистрация: 04.04.2016
Сообщений: 4
По умолчанию

Дело в том, что не получается объединить больше, чем две фигуры, как это на рисунке: то есть несколько квадратов и кривая.

Последний раз редактировалось ViktorGugo; 04.04.2016 в 20:04.
ViktorGugo вне форума Ответить с цитированием
Старый 04.04.2016, 21:30   #8
Alex11223
Старожил
 
Аватар для Alex11223
 
Регистрация: 12.01.2011
Сообщений: 19,500
По умолчанию

Так например:
Код:
<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="525">
    <Window.Resources>
        <PathGeometry x:Key="fig" >
            <PathFigure IsClosed="false" StartPoint="-10,180" >
                <QuadraticBezierSegment Point1="80,0" Point2="215,180" />
            </PathFigure>
        </PathGeometry>
        <GeometryGroup x:Key="rect1">
            <RectangleGeometry Rect="0,30,100,150"></RectangleGeometry>
        </GeometryGroup>
        <GeometryGroup x:Key="rect2">
            <RectangleGeometry Rect="100,30,100,150"></RectangleGeometry>
        </GeometryGroup>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <Path Grid.Row="0" Margin="25" Fill="Orange" Data="{StaticResource rect1}"/>

        <Path Grid.Row="0" Margin="25" Fill="Green" Data="{StaticResource rect2}"/>

        <Path Grid.Row="0" Margin="25" Stroke="Blue" Data="{StaticResource fig}" />

        <Path Grid.Row="1" Margin="25" Fill="Orange">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Intersect"
                    Geometry1="{StaticResource rect1}"
                    Geometry2="{StaticResource fig}">
                </CombinedGeometry>
            </Path.Data>
        </Path>
        <Path Grid.Row="1" Margin="25" Fill="Green">
            <Path.Data>
                <CombinedGeometry GeometryCombineMode="Intersect"
                    Geometry1="{StaticResource rect2}"
                    Geometry2="{StaticResource fig}">
                </CombinedGeometry>
            </Path.Data>
        </Path>
    </Grid>
</Window>
Ушел с форума, https://www.programmersforum.rocks, alex.pantec@gmail.com, https://github.com/AlexP11223
ЛС отключены Аларом.
Alex11223 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
[WPF][C#] Одновременная анимация 100-а и больше объектов Dj_SheLL WPF, UWP, WinRT, XAML 3 05.11.2015 10:38
Создание нескольких (группы) 3D объектов в wpf p0keT WPF, UWP, WinRT, XAML 4 05.03.2015 17:37
Перетасовка объектов на форме jonyroww Помощь студентам 0 28.05.2014 16:25
Положение объектов на форме Port 111 Общие вопросы Delphi 8 12.01.2009 22:11