0

I want to setup a background image for a page. Right now I am using

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
        x:Class="M.LaunchPage"
        Title ="M" BackgroundImage="Mars.jpg">
    <ContentPage.Content> 
      <StackLayout Padding="10,0,10,10" > 
        <Button VerticalOptions="CenterAndExpand" Text="Sign Up" TextColor="White" Clicked="OnSignUp" BackgroundColor="Maroon" />  
        <StackLayout Padding="10,0,10,10" Orientation="Horizontal" VerticalOptions="EndAndExpand" />
      </StackLayout> 
    </ContentPage.Content>
</ContentPage>

This works well but the image is being filled multiple times to fit the screen. Cn anyone suggest better code so that I can fit the image on the page perfectly?

Thanks.

Rui Marinho
  • 1,692
  • 12
  • 20
TheDeveloper
  • 1,127
  • 1
  • 18
  • 55

2 Answers2

1

This is platform dependent, for example on iOS the following is used in the Form's iOS's PageRender:

View.BackgroundColor = UIColor.FromPatternImage(UIImage.FromBundle(bgImage));

The View.BackgroundColor will end up tiling your image when it is smaller the UIController's View dimensions as FromPatternImage is designed to be used with a small repeating pattern (for memory and draw performance reasons) and not full screen/page images.

In order for this auto-tiling not to happen, you would be to assign the background image in code based upon the device's screen resolution and page size at runtime and not statically assign it in XAML.

Note: You could bind the BackgroundImage property in a ViewModel where the calculations of which image to use could be done.

SushiHangover
  • 73,120
  • 10
  • 106
  • 165
  • I tried to do something like `var beachImage = new Image { Aspect = Aspect.AspectFit, Source= ImageSource.FromFile("Mars.jpg")};` in codebehind but backgroundimage only accept string values(Image name).. If we directly give image name in backgroundimage in Xamarin form page then how can we edit its properties to set the aspect ratio property ? – TheDeveloper Aug 10 '16 at 13:40
  • @AzharAli You can not, you need to supply a *different* image, one that matches your page dimensions from your app bundle (AndroidAsset, BundleResource, etc..) or transform a base image at runtime into one that matches your dimension requirements and use that resulting new image. – SushiHangover Aug 10 '16 at 13:47
  • Can you be more specific about how I can transform my image at runtime to match device dimentions ? – TheDeveloper Aug 10 '16 at 14:27
1

You should use each platform specifications, for example in iOS you need to have Mars@2x.jpg and Mars@3x.jpg,in our platform project in Forms you can specify from "Mars" it will pick the correct one.

On Android set the image in the correct dpi folder.

Rui Marinho
  • 1,692
  • 12
  • 20