WPF borderless application with round corners
I have created a WPF app that is borderless and have an image that I want to be my background. I created my image in Paint, so I did not have an option to make the corners transparent. I would like to make the application have rounded corners, but I am not getting the expect results with XAML. I have tried adding a border to get the desired effect but when I run the applica开发者_StackOverflow社区tion, the image is still in front of the border. Here is my code. What am I doing wrong?
<Border BorderBrush="Black" CornerRadius="15,15,15,15" BorderThickness="1,1,1,1" Width="242" Height="426">
<Grid>
<Image Height="425" Name="image1" Stretch="Fill" Width="240" Source="/Test;component/Test.png" />
<Grid Height="334" HorizontalAlignment="Left" Margin="24,39,0,0" Name="grid1" VerticalAlignment="Top" Width="198" />
</Grid>
</Border>
these settings in the window will make it transparent:
WindowStyle="None"
AllowsTransparency="True"
Background="Transparent"
and then just set the background of the Border to be the image:
<Border BorderBrush="Transparent" BorderThickness="1" CornerRadius="15">
<Border.Background>
<ImageBrush>
<ImageBrush.ImageSource>
<BitmapImage UriSource="/Test;component/Test.png" />
</ImageBrush.ImageSource>
</ImageBrush>
</Border.Background>
</Border>
I think you need to add ClipToBounds="True" to the image.
Here is a special border where ClipToBounds works perfectly. If you change in Erez's answer the "Border" to "ClippingBorder" then it should work.
''' <Remarks>
''' As a side effect ClippingBorder will surpress any databinding or animation of
''' its childs UIElement.Clip property until the child is removed from ClippingBorder
''' </Remarks>
Public Class ClippingBorder
Inherits Border
Protected Overrides Sub OnRender(ByVal dc As DrawingContext)
OnApplyChildClip()
MyBase.OnRender(dc)
End Sub
Public Overrides Property Child() As UIElement
Get
Return MyBase.Child
End Get
Set(ByVal value As UIElement)
If Me.Child IsNot value Then
If Me.Child IsNot Nothing Then
' Restore original clipping
Me.Child.SetValue(UIElement.ClipProperty, _oldClip)
End If
If value IsNot Nothing Then
_oldClip = value.ReadLocalValue(UIElement.ClipProperty)
Else
' If we dont set it to null we could leak a Geometry object
_oldClip = Nothing
End If
MyBase.Child = value
End If
End Set
End Property
Protected Overridable Sub OnApplyChildClip()
Dim _child As UIElement = Me.Child
If _child IsNot Nothing Then
_clipRect.RadiusX = InlineAssignHelper(_clipRect.RadiusY, Math.Max(0.0, Me.CornerRadius.TopLeft - (Me.BorderThickness.Left * 0.5)))
_clipRect.Rect = New Rect(_child.RenderSize)
_child.Clip = _clipRect
End If
End Sub
Private _clipRect As New RectangleGeometry()
Private _oldClip As Object
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function
End Class
And you can use http://www.developerfusion.com/tools/convert/vb-to-csharp/ if you like C# better.
精彩评论