I have a background image on my start page that is being stretched to fit the screen when the app runs. I'm trying to avoid this stretching since it looks awful.
I created a Page Renderer class inside the android project:
[assembly: ExportRenderer(typeof(Page), typeof(CustomPageRenderer))]
namespace ChoiceBasedStoryGame.Droid
{
public class CustomPageRenderer : PageRenderer
{
public CustomPageRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
base.OnElementChanged(e);
var activity = this.Context as Activity;
activity.Window.SetBackgroundDrawable(Resources.GetDrawable(Resource.Drawable.cyberpunk_hacker));
var imageView = activity.FindViewById<ImageView>(Android.Resource.Id.Content);
imageView.SetScaleType(ImageView.ScaleType.CenterCrop);
}
}
}
I would like to reference this in my start page:
namespace ChoiceBasedStoryGame
{
public class StartPage : ContentPage
{
public StartPage()
{
var renderer = new CustomPageRenderer(this.Context);
this.BackgroundImageSource = "cyberpunk_hacker.png";
this.Renderer = new CustomPageRenderer(this.Context);
I'm getting errors with the namespace 'CustomPageRenderer' not existing.
But this gives a similar error with 'Droid'. I verified the reference was correct in the android properties.
I've tried adding the 'using' at the top:
using ChoiceBasedStoryGame.Droid;
Is there an easier way to set the scale for a background image to not stretch?
Thank you.
CodePudding user response:
At first, if you want to use the custom renderer only for the StartPage, you can change the [assembly: ExportRenderer(typeof(Page), typeof(CustomPageRenderer))]
to the [assembly: ExportRenderer(typeof(StartPage), typeof(CustomPageRenderer))]
.
And you can check the official document about the Customizing a ContentPage for more details.
In addition, there are many other methods about how to set the page's background image appropriately. Such as you can use the image control in the grid as my old answer did. You can also refer to this case about changing aspect ratio of background image in Xamarin.Forms while keeping contents centered