开发者

Display only certain portion of an image file in an Image

开发者 https://www.devze.com 2023-03-17 18:45 出处:网络
I want to be able to have an Image object render just a portion an image, that I will control programatically. For example, this is what I have so far:

I want to be able to have an Image object render just a portion an image, that I will control programatically. For example, this is what I have so far:

Display only certain portion of an image file in an Image

开发者_Python百科<Image Grid.Column="1" Grid.Row="1" Grid.RowSpan="3" Height="160" 
    HorizontalAlignment="Right" Name="avatarImage" Stretch="None" 
    VerticalAlignment="Center" Width="160" 
    Source="/Crystal%20Cloud;component/data/images/characters.png" 
    Margin="0,0,40,0" />

I want to only render one of the characters at a time, and use the button to change which one it renders. Can I do this, and if so, how?


You can definitely use the ImageBrush.Transform to extract the portion of the bitmap that you are interested in, and if you do not require very high frame rates that is the way to go.

However if you are going to need to optimize the frame rate then you can dynamically extract the individual bitmaps from the sprite sheet and cache those bitmaps and display them as required. The blog post below provides some code that you can use to extract the individual bitmaps, that you can then cache.

http://taylorza.blogspot.com/2009/08/silverlight-spritesheet-management-with.html

Remember the key to performance here is that you cache the bitmaps and do not go through all the trouble of extracting them each time you need a new image.


You also can place your image inside a Canvas and define a clip for it (visible portion). Then for animating the character you can programatically change the Top and Left of the image in time intervals:

<Canvas Width="200" Height="100">       
    <Canvas.Clip>
        <RectangleGeometry Rect="0, 0, 200, 100"/>
    </Canvas.Clip>

    <Image x:Name="imgCharacter" Source="..." Canvas.Left="..." Canvas.Top="..." />
</Canvas>


imgCharacter.SetValue(Canvas.LeftProperty, currentFrame.Left);
imgCharacter.SetValue(Canvas.LeftProperty, currentFrame.Top);
0

精彩评论

暂无评论...
验证码 换一张
取 消