How to add a image into stringlist? - qt4.7

I am in need to add a image into a string list that contains item which is parsed value. Whether can i add an image in-between two strings in qt??
Here is my sample code that i used and tried to add an image!!!
myImage(://image.png);
strList << sender + myImage + "\n" + Receiver
myImage is the place where i need to add the image.. Is this possible in QT?
strlist is the QStringList which i have declared.
I am not getting the image when i run them.
Please find me a solution for this!!!!
Thanks in Advance and Regards,
Naufal.A

I am assuming that the myImage is of type QImage. In that case what you doing is illegal to start from. Add the url of the image (as u have ://image)

QStringList is a typedef for QList - it means it can store only QString objects, nothing else!
As Neox suggested you should rather store the QImage's url in the list.
Or if your question is about how to serialize the QImage (how to store it to QString which can be added to a QStringList) the answer is QImage's save() method - the official documentation gives a full example in the description of QImage save()
url: http://qt-project.org/doc/qt-4.8/qimage.html#save-2
code:
QImage image;
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG"); // writes image into ba in PNG format
This will save/serialize the given QImage image to the QByteArray ba.
QByteArray can be simply converted to QString - just use the QString's QByteArray constructor like:
QByteArray myByteArray;
QString myStringFromBA(myByteArray);

Related

How to convert image name to string after randomly selecting from folder

I'm quite new to progamming. So here's my function to select a random image in my drawable folder.
fun generateimage(index:Int)
{var images=arrayOf(R.drawable.img1,....)
main_imageView.setImageResource(images[index])
This works as an image is shown randomly every time I start the application. But I would like to be able to know which image was selected. Preferably from retrieving the image name to string.
Possible duplicate of
How to get drawable name from imageView
However, a better implementation would be to have the value in a list of int and put your R.drawable items inside it. That was you can access which element is being shown.
You can do something like this:
fun main() {
val arrayImages = arrayOf("image1", "image2", "image3", "image4", "image5")
// in your case actual images.
val randomIndex = (0..arrayImages.size).random()
val randomImage = arrayImages[randomIndex]
println(randomImage) // in your case: main_imageView.setImageResource(randomImage)
}
Note that you need to assign the variable of randomImage so you can access it later on. I don't know what type "R.drawable.img1" is, but the object you set inside this array has to store the name of the file, so you can retrieve it that way.

How can I read a string directly into a variable? Java, slick

I want to program some kind of game where the player has to name loacations shown on a map. I am using the slick library.
My problem is that I need some way to get the keyboard input from the player. I tried it with InputDialog from JOptionPane but I do not really like it. I would rather have the string appear on some part of the screen. But I do not have any idea how I can read from the keyboard directly into a variable that should be drawn on the screen. I thought that it would be possible to use streams but if I try to get some examples, they are always about reading from files and I do not know how to use that for reading from keyboard.
String answer;
public void render(GameContainer gameContainer, StateBasedGame sbGame, Graphics g){
g.drawString(answer, 50, 50);
}
public void update(GameContainer gameContainer, StateBasedGame sbGame, int delta){
//user types something which I now call "inputFromUser"
//it does not appear anywhere before the string is drawn on the screen.
answer = inputFromUser;
}
Something like a Scanner does not work for me because the user has to type that into the console, and I want him to type it "directly into the game" like it works with a textfield. (But I do not want to use a textfield.)
I have one way to accomplish that but it's fairly resource intensive. First create a global variable to keep track of the current letters. now create a new method that runs through all of the keys to check if they are down
private String totalString;
private void handelUserInput(Input input){
if(input.isKeyDown(Input.KEY_BACK)){
totalString = totalString.substring(0, totalString.length() - 1);
}
if(input.isKeyDown(Input.KEY_A)){
totalString += "a";
}
if(input.isKeyDown(Input.KEY_B)){
totalString += "b";
}
...etc
}
next create an input handler in the update loop to pass into the handle input method.
public void update(GameContainer gc, StateBasedGame sbg, int delta)throws SlickException {
Input input = gc.getInput();
handelUserInput(input);
}
and then print the string somewhere on your window in the render loop. by the way the Input class is built into slick.

QWebFrame print in a separate thread

In my qt application I'm printing some large html code from a QWebFrame (mainFrame from a QWebPage). The html code contains some inline images and takes a while to be printed. Therefore I tried to put the print call into a separate thread to keep the gui responsive. As mentioned in the docs I thought this should be possible (Painting in threads).
But I still get the famous "QPixmap: It is not safe to use pixmaps outside the GUI thread"
My code to print is as follows:
void PrintDialog::paintRequested(QPrinter *printer) {
futureWatcher = new QFutureWatcher<void>();
QEventLoop q;
connect(futureWatcher, SIGNAL(finished()), &q, SLOT(quit()), Qt::UniqueConnection);
futureWatcher->setFuture(QtConcurrent::run(m_webPage->mainFrame(), &QWebFrame::print, printer));
q.exec();
}
To clarify all objects reside in the gui thread and the html gets generated before. The images get inlined like follows:
QImage image
QByteArray ba;
QBuffer buffer(&ba);
buffer.open(QIODevice::WriteOnly);
image.save(&buffer, "PNG");
QString html = "<img src=\"data:image/png;base64," + QString(ba.toBase64() + "\"/>";
So what am I doing wrong here? Is it that the QWebFrame internally uses some QPixmaps? Is there any solution for using the QWebFrame::print call in another thread?

objective c appending string cocos2d

Hello I am writing an application and I want to create a string.
so I use that
NSString *scoreString;
NSString *cupCakesPassedString;
NSString *cupCakes;
int cupCakesPassed;
int totalCupCakesPerLevel;
-(void)spriteMoveFinished:(id)sender {
CCSprite *sprite = (CCSprite *)sender;
[self removeChild:sprite cleanup:YES];
if (sprite.position.y <= 0) {
sprite.position = ccp( sprite.position.x,768 );
score+=5;
scoreString=[NSString stringWithFormat:#"%i",score];
[label setString:scoreString];
cupCakesPassed++;
cupCakesPassedString=[NSString stringWithFormat:#"%i",cupCakesPassed];
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:totalCupCakes];
[passingCupCakes setString:cupCakes];
}
}
it crashes!! but if use another string like scoreString it works...
in init method I have
totalCupCakesPerLevel=30;
scoreString=[NSString stringWithFormat:#"%i",score];
cupCakesPassedString=[NSString stringWithFormat:#"%i",cupCakesPassed];
totalCupCakes = [NSString stringWithFormat:#"%i",7];
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:totalCupCakes];
if I do this
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:scoreString];
I also has in init method that
cupCakes=[[cupCakesPassedString stringByAppendingString:#"/"]stringByAppendingString:totalCupCakes];
and actually works...until the method is called.
the numbers might be wrong but are for testing purposes
it seems that the problem is with string totalCupCakes,since even if I use #"test" works but what is wrong with that string?
Using a string method like this:
cupcakes = [NSString stringWithFormat:#"%d/%d", cupCakesPassed, totalCupCakes];
Would be simpler to use instead of the appending strings.
If I understand right, all your problems are because of non-retained strings. All stringWith... constructors of NSString class returns autoreleased objects. Retain them after creation and release in your dealloc method.
In your case to the moment of calling method, strings are deallocated and are not valid objects

iOS 5 + GLKView: How to access pixel RGB data for colour-based vertex picking?

I've been converting my own personal OGLES 2.0 framework to take advantage of the functionality added by the new iOS 5 framework GLKit.
After pleasing results, I now wish to implement the colour-based picking mechanism described here. For this, you must access the back buffer to retrieve a touched pixel RGBA value, which is then used as a unique identifier for a vertex/primitive/display object. Of course, this requires temporary unique coloring of all vertices/primitives/display objects.
I have two questions, and I'd be very grateful for assistance with either:
I have access to a GLKViewController, GLKView, CAEAGLLayer (of the GLKView) and an EAGLContext. I also have access to all OGLES 2.0
buffer related commands. How do I combine these to identify the color
of a pixel in the EAGLContext I'm tapping on-screen?
Given that I'm using Vertex Buffer Objects to do my rendering, is there a neat way to override the colour provided to my vertex shader
which firstly doesn't involve modifying buffered vertex (colour)
attributes, and secondly doesn't involve the addition of an IF
statement into the vertex shader?
I assume the answer to (2) is "no", but for reasons of performance and non-arduous code revamping I thought it wise to check with someone more experienced.
Any suggestions would be gratefully received. Thank you for your time
UPDATE
Well I now know how to read pixel data from the active frame buffer using glReadPixels. So I guess I just have to do the special "unique colours" render to the back buffer, briefly switch to it and read pixels, then switch back. This will inevitably create a visual flicker, but I guess it's the easiest way; certainly quicker (and more sensible) than creating a CGImageContextRef from a screen snapshot and analyzing that way.
Still, any tips as regards the back buffer would be much appreciated.
Well, I've worked out exactly how to do this as concisely as possible. Below I explain how to achieve this and list all the code required :)
In order to allow touch interaction to select a pixel, first add a UITapGestureRecognizer to your GLKViewController subclass (assuming you want tap-to-select-pixel), with the following target method inside that class. You must make your GLKViewController subclass a UIGestureRecognizerDelegate:
#interface GLViewController : GLKViewController <GLKViewDelegate, UIGestureRecognizerDelegate>
After instantiating your gesture recognizer, add it to the view property (which in GLKViewController is actually a GLKView):
// Inside GLKViewController subclass init/awakeFromNib:
[[self view] addGestureRecognizer:[self tapRecognizer]];
[[self tapRecognizer] setDelegate:self];
Set the target action for your gesture recognizer; you can do this when creating it using a particular init... however I created mine using Storyboard (aka "the new Interface Builder in Xcode 4.2") and wired it up that way.
Anyway, here's my target action for the tap gesture recognizer:
-(IBAction)onTapGesture:(UIGestureRecognizer*)recognizer {
const CGPoint loc = [recognizer locationInView:[self view]];
[self pickAtX:loc.x Y:loc.y];
}
The pick method called in there is one I've defined inside my GLKViewController subclass:
-(void)pickAtX:(GLuint)x Y:(GLuint)y {
GLKView *glkView = (GLKView*)[self view];
UIImage *snapshot = [glkView snapshot];
[snapshot pickPixelAtX:x Y:y];
}
This takes advantage of a handy new method snapshot that Apple kindly included in GLKView to produce a UIImage from the underlying EAGLContext.
What's important to note is a comment in the snapshot API documentation, which states:
This method should be called whenever your application explicitly
needs the contents of the view; never attempt to directly read the
contents of the underlying framebuffer using OpenGL ES functions.
This gave me a clue as to why my earlier attempts to invoke glReadPixels in attempts to access pixel data generated an EXC_BAD_ACCESS, and the indicator that sent me down the right path instead.
You'll notice in my pickAtX:Y: method defined a moment ago I call a pickPixelAtX:Y: on the UIImage. This is a method I added to UIImage in a custom category:
#interface UIImage (NDBExtensions)
-(void)pickPixelAtX:(NSUInteger)x Y:(NSUInteger)y;
#end
Here is the implementation; it's the final code listing required. The code came from this question and has been amended according to the answer received there:
#implementation UIImage (NDBExtensions)
- (void)pickPixelAtX:(NSUInteger)x Y:(NSUInteger)y {
CGImageRef cgImage = [self CGImage];
size_t width = CGImageGetWidth(cgImage);
size_t height = CGImageGetHeight(cgImage);
if ((x < width) && (y < height))
{
CGDataProviderRef provider = CGImageGetDataProvider(cgImage);
CFDataRef bitmapData = CGDataProviderCopyData(provider);
const UInt8* data = CFDataGetBytePtr(bitmapData);
size_t offset = ((width * y) + x) * 4;
UInt8 b = data[offset+0];
UInt8 g = data[offset+1];
UInt8 r = data[offset+2];
UInt8 a = data[offset+3];
CFRelease(bitmapData);
NSLog(#"R:%i G:%i B:%i A:%i",r,g,b,a);
}
}
#end
I originally tried some related code found in an Apple API doc entitled: "Getting the pixel data from a CGImage context" which required 2 method definitions instead of this 1, but much more code is required and there is data of type void * for which I was unable to implement the correct interpretation.
That's it! Add this code to your project, then upon tapping a pixel it will output it in the form:
R:24 G:46 B:244 A:255
Of course, you should write some means of extracting those RGBA int values (which will be in the range 0 - 255) and using them however you want. One approach is to return a UIColor from the above method, instantiated like so:
UIColor *color = [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha/255.0f];

Resources