简体   繁体   中英

Xamarin local image from file or resources

I cannot get my images to show up in Android at all. I have tried with ImageSource.FromFile and ImageSource.FromResource.

I have read "Working with Images" several times and just don't see what I am doing wrong.

From File Example

        var myImage = new Image() {
            Aspect = Aspect.AspectFill,
            Source = ImageSource.FromFile("backdrop.jpg")
        };

        RelativeLayout layout = new RelativeLayout();

        layout.Children.Add(myImage,
            Constraint.Constant(0),
            Constraint.Constant(0),
            Constraint.RelativeToParent((parent) => { return parent.Width; }),
            Constraint.RelativeToParent((parent) => { return parent.Height; }));

        Content = layout; 

在此处输入图片说明

The Build Action is set to: AndroidResource

I always get the NullReference exception with this path

在此处输入图片说明

FromResource example

        var myImage = new Image()
        {
            Aspect = Aspect.AspectFill,
            Source = ImageSource.FromResource("TTMD_Mobile.Droid.backdrop.jpg")
        };

        RelativeLayout layout = new RelativeLayout();

        layout.Children.Add(myImage,
            Constraint.Constant(0),
            Constraint.Constant(0),
            Constraint.RelativeToParent((parent) => { return parent.Width; }),
            Constraint.RelativeToParent((parent) => { return parent.Height; }));

        Content = layout;

The Build Action is set to: Embedded Resource

With the FromResource I don't get any exception, just the image doesn't show.

I am fairly new to Xamarin and Android development, my apologies if this has been addressed, I couldn't find a working solution.

EDIT: I do not believe this is a duplicate of that question, I have my images in their correct locations I believe.

Create images folder in Xamarin forms project and then add Image to that folder. In properties for the image, set "Build Action" to "Embedded resource"

For ex: My project name is XTest. Path to image is: XTest/images/pic.jpg

显示路径的解决方案资源管理器

In you cs file you can now use it like this.

    imgLocal.Source = ImageSource.FromResource("XTest.images.pic.jpg");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM