Unity changing from game object to ui Image - image

In unity I am fetching a UI image through GameObject.Find() However when I try to change the value of another image component to the result of the game object find I get the error:
Cannot implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.UI.Image' \[Assembly-CSharp\]csharp(CS0029)
Code:
Image image;
image = GameObject.Find("the other image");
Is there a way to fetch a UI Image game object through just it's name without it being set to a generic game object?

You are attempting to assign the value of a image to a gameObject, you simply need to get the image
Image image;
var imageGameObject = GameObject.Find("the other image");
if(imageGameObject == null)
{
//couldn't find the gameobject
}
image = imageGameObject.GetComponenet<Image>();
to get the actual image component

Related

SwiftUI Image does not display image from existing file

In my SwiftUI app I have a view for people to edit a book's metadata, such as its title and author. In this view I have an image view that shows the book's cover image.
struct ImageView: View {
#Binding var book: Book
var body: some View {
// coverFile is the URL to the image file.
let image = NSImage(byReferencing:
book.metadata.coverFile)
Image(nsImage: image)
.aspectRatio(contentMode: .fit)
}
}
When I open a book that I've set a cover image and open the metadata editor, the image view displays nothing. The metadata editor has a button to choose a cover image. When I click the button and choose an image file from the file importer, the image appears in the image view. If I close the book, reopen it, and open the metadata editor, the image appears in the image view. But if I restart the app, open the book, and open the metadata editor, the image view displays nothing.
I have tried the various NSImage initializers. I tried building the image from a Data object and from NSBitmapImageRep.
extension Book {
func coverImage() -> NSImage {
do {
let data = try Data(contentsOf: metadata.coverFile)
return NSImage(data: data) ?? NSImage()
} catch {
Swift.print("Error reading the image data. Error: \(error)")
}
return NSImage()
}
}
struct ImageView: View {
#Binding var book: Book
var body: some View {
let image = book.coverImage()
Image(nsImage: image)
.aspectRatio(contentMode: .fit)
}
}
But when I set a breakpoint in the image view and check the image variable, it's either nil or invalid. When I check the coverFile variable, it displays the proper URL, including the .png extension.
In an AppKit version of this app, I have the same code to create the NSImage, and the image displays in the image view.
According to Apple's documentation, the NSImage byReferencing function does not attempt to retrieve the data from the specified URL or create any image representations from that data until an app attempts to draw the image or request information about it. How do I get the SwiftUI view to trigger retrieving the image data so it displays in the image view?
UPDATE
I created a computed property for the image in the ImageView struct.
var image: NSImage {
do {
let data = try Data(contentsOf: book.metadata.coverFile)
return NSImage(data: data) ?? NSImage()
} catch {
Swift.print("Error creating the image. Error: \(error)")
}
return NSImage()
}
When I run this code, the try Data call throws an exception, the catch block runs, and the following error message is printed in Xcode's Console:
Error creating the image. Error: Error Domain=NSCocoaErrorDomain
Code=257 "The file “ImageFile” couldn’t be opened because you
don’t have permission to view it."
Choosing a file from the file importer causes the data to be created properly. I have read/write permission for the folder where the image file is.
From what I understand the problem boils down to lazily initializing the NSImage.
Have you tried using init(contentsOfFile:) or init(contentsOf:)? It does not initialize it lazily therefore should not cause this problem.
The image does not display because of a file permissions problem. If I turn on the App Sandbox and give the app Read access to the Pictures folder, the cover image appears when I open the metadata editor.

How to convert BitmapImage to WriteableBitmap in Universal application for windows 10?

I am implementing a Universal Windows Application on Windows 10 using MVVM.
I have a file picker allowing me to choose an image. This image is displayed in an Image Control. The source of the Image Control is bound to a property in my view model. This property is a byte array. I need a converter to convert the BitmapImage in a Byte Array.
I have read lots of things but can't found something working.
I have found interesting stuff on https://writeablebitmapex.codeplex.com/
but if i want to use this package i need a WriteableBitmap and not a BitmapImage.
Thank you in advance for your help.
You can load the image to a WriteableBitmap object straight from the file.
var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add(".jpg");
var result = await filePicker.PickSingleFileAsync();
if (result != null)
{
using (IRandomAccessStream stream = await result.OpenAsync(FileAccessMode.Read))
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(stream);
WriteableBitmap bmp = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
bmp.SetSource(stream);
// show the image in the UI if you want.
MyImage.Source = bmp;
}
}
This way you have the WriteableBitmap and you can use the WriteableBitmapEx library.

How to fit image to center while using TouchImageView?

I have a gallery application that needs to zoom and pan. Instead of using default imageview , I found a sample touchmageview on internet and copied it. I called my images with TouchImageView and now i can zoom and pan the images that I called from my drawable folder. Then I added gallery to my project. Now the problem is that I can not fit the images to the screen.When I use scaletype.center then it fits the image to the screen but now zoom and pan features are not working. This is my gallerylistener ;
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(Display.this, "Your selected position = " + position, Toast.LENGTH_SHORT).show();
// show the selected Image
img.setScaleType(ScaleType.CENTER_INSIDE);
img.setImageResource(Imgid[position]);
}
});
As you see , if I add img.setScaleType(ScaleType.CENTER_INSIDE); then the TouchImageView class doesn't work and I am not able to zoom and pinch and pan etc.. It only display the image. When I delete this code , then I can zoom but then when I change the picture to another one , the new one has the previous image's size. But I want to fit them to the center. Is there any way to reset the scaletype before calling the new image ?
By the way I have only one imageview in xml.
There is a similar question on this link but the solution did not work for me.
how to get setScaleType(ImageView.ScaleType.FIT_CENTER) effect using setScaleType(ImageView.ScaleType.MATRIX)

Getting JPanel's Image

I'm having problems creating a BufferedImage from an offscreen JPanel. Specifically, I'm trying a draw the image of a JPanel (which contains some Java3D elements) as a background image for an application I'm working on.
I've found several threads describing how to do get a JPanel's Image by painting the JPanel to a BufferedImage's graphics context, but when I draw the BufferedImage, all I get is a big white rectangle.
Here's my code:
SimpleWorld j3DPanel; // a custom JPanel that contains some simple Java3D elements
// CONSTRUCTOR
public GameBackgroundObject()
{
super();
// Here I set up a JPanel that contains some Java3D elements.
j3DPanel = new SimpleWorld();
j3DPanel.setSize(mainLevel.SCREENW, mainLevel.SCREENH);
j3DPanel.setBounds(0,0,mainLevel.SCREENW, mainLevel.SCREENH);
j3DPanel.doLayout();
j3DPanel.validate();
}
protected void draw(Graphics2D parentComponentGraphics, ...)
{
super.draw(parentComponentGraphics, ...);
int w = j3DPanel.getWidth();
int h = j3DPanel.getHeight();
BufferedImage j3DImg = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = j3DImg.createGraphics();
j3DPanel.paint(g);
parentComponentGraphics.drawImage(j3DImg, null, null);
}
Also, I've tried adding my JPanel to the contents of a JFrame. It works there and shows the rendered Java3D elements correctly. However, I just get this big white rectangle whenever I try to get the BufferedImage of the JPanel and draw that image.
Drawing a Java 3D scene probably fails because its Canvas3D component is heavyweight. Using the lightweight panel 'com.sun.j3d.exp.swing.JCanvas3D' might solve this problem. Its use is a bit tricky. See the corresponding Java 3D sample 'JCanvas3DExample' or try one of the derived works from here http://www.interactivemesh.org/testspace/j3dmeetsswing.html#leightweight
Try calling:
j3DPanel.paintComponent(g);
instead of:
j3DPanel.paint(g);

Image gets clipped while changing orientation using Qt

HI all,
I wnt to develop an ImageViewer using qt. I m trying to resize big images by scaling them. My problem is , when i change the screen orientation some part of the image gets clipped and also if i open the image in landscape mode, by default the size of image remains small even when i change back to portrait mode. What am i Doin wrong?
Please help me out. Heres the code dat i hv written
ImageViewer::ImageViewer()
{
setAttribute(Qt::WA_DeleteOnClose);
QAction *back = new QAction(this);
back->setText(QString("Back"));
connect(back,SIGNAL(triggered()),this,SLOT(close()));
back->setSoftKeyRole(QAction::PositiveSoftKey);
addAction(back);
imageLabel = new QLabel();
imageLabel->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);
imageLabel->setAlignment(/*Qt::AlignLeft|*/Qt::AlignCenter);
QWidget *widget = new QWidget;
layout=new QStackedLayout();
layout->addWidget(imageLabel);
widget->setLayout(layout);
setCentralWidget(widget);
}
void ImageViewer::showImage(QString filePath)
{
QImageReader reader;
reader.setFileName(filePath);
QSize imageSize = reader.size();
imageSize.scale(size(), Qt::KeepAspectRatio);
reader.setScaledSize(imageSize);
QImage image = reader.read();
imageLabel->setPixmap(QPixmap::fromImage(image));
imageLabel->adjustSize();
}
You should re-implement QLabel's resizeEvent or install event filter to it and handle QResizeEvent there
The content of showImage method should go to handler of a resize event.
Currently you are using size() of ImageViewer widget (which seems to be derived from QMainWindow), it's better to use imageLabel.size(); or the best QResizeEvent::size() as this will prevent a problem if you will change UI layout in future.

Resources