UIImageView image not showing up at all - iphone

im using the followng method , to display image when a timestamp detecetd , am using
dispatch_async(dispatch_get_main_queue(), to do UIImageView , its never works its should open a new screen full size image that it ,
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *myImage = [UIImage imageNamed:#"img.jpg"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
[myImageView setFrame:CGRectMake(0, 0, 100, 200)];
[myImageView release];
;
});
my full code
- (void) onPayload:(PayloadEvent *) event
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString *header = #"[OnPayload] ";
if (event.payloadType == TYPE_IDENTIFIED)
{
if ((event.contentID != -1) && (event.timeStamp == -1))
{
[mUI performSelectorOnMainThread: #selector(Trace:) withObject:[NSString stringWithFormat:#"%# StaticID detected: %x\t\tConfidence: %f\n", header,(int)event.contentID, event.confidence] waitUntilDone:NO];
}
if ((event.timeStamp != -1) && (event.contentID == -1))
{
[mUI performSelectorOnMainThread: #selector(Trace:) withObject:[NSString stringWithFormat:#"%# Timestamp detected: %f\t\tConfidence: %f\n", header, event.timeStamp, event.confidence] waitUntilDone:NO];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *myImage = [UIImage imageNamed:#"img.jpg"];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:myImage];
[myImageView setFrame:CGRectMake(0, 0, 100, 200)];
[myImageView release];
; });

You never add myImageView to any view as a subview.

Try to use this one in your code.
[self.view addSubview:myImageView];

You are creating an ImageView, assigning an Image to it and releasing the ImageView. In other words, you're not displaying the ImageView anywhere.
If you can't do something like [self.view addSubview:imageView], it means that you're not running this code on a UIViewController subclass.
You basically need to add this ImageView you're creating as a subview for the current view before releasing it.
In which class are you running this code? Do you know which View Controller is currently being displayed?

Related

Show activity indicator with lazy loading using AsyncImageView classes

I am using AsyncImageView classes to apply lazy loading on UITableView. And want to apply activity indicator on image view until the image is loaded on cell. Below is my code i am trying.
// AsyncIamgeView.m
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//[connection release];
UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
indicator.center = CGPointMake(15, 15);
connection=nil;
if ([[self subviews] count]>0) {
[[[self subviews] objectAtIndex:0] removeFromSuperview];
}
UIImage *imgData = [UIImage imageWithData:data];
UIImageView* imageView = [[UIImageView alloc]init];
[imageView addSubview:indicator];
[indicator startAnimating];
if(imgData == nil)
{
imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"NoImagenew.png"]];
//[indicator stopAnimating];
}
else{
imageView = [[UIImageView alloc] initWithImage:imgData];
// [indicator stopAnimating];
}
//imageView.contentMode = UIViewContentModeScaleAspectFit;
//imageView.autoresizingMask = ( UIViewAutoresizingFlexibleWidth || UIViewAutoresizingFlexibleHeight );
//[imageView sizeToFit];
[self addSubview:imageView];
imageView.frame = self.bounds;
//imageView.frame = CGRectMake(0, 0, 85, 94);
[imageView setNeedsLayout];
[self setNeedsLayout];
//[data release];
data=nil;
}
// cellForRowAtIndexPath method.
asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(1, 3, 85, 54)];
[asyncImageView loadImageFromURL:[NSURL URLWithString:imageUrlString]];
[cell.contentView addSubview:asyncImageView];
This code shows activity indicator but when image is loaded after that not before loading images. Please guide for above.
You have to create AsyncImageView object instead of UIImageView, then it will automatically add indicator to your view
AsyncImageView *imageView = [[AsyncImageView alloc] initWithFrame:CGRectMake(1, 3, 85, 54)];
[cell addSubview:imageView];
//cancel loading previous image for cell
[[AsyncImageLoader sharedLoader] cancelLoadingImagesForTarget:imageView];
//load the image
imageView.imageURL = [imageURLs objectAtIndex:indexPath.row];
Here is an example of this
Currently you are adding activity indicator when your image is downloaded.
Here is the simple idea, hope you can implement this in your code
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when your connection receives a response
// add your activity indication here and start animating
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// This method is called when your image is downloaded.
// remove your activity indicator or stop animating here
}
Hope u downloaded AsyncImageView from https://github.com/nicklockwood/AsyncImageView. By default, it has the feature to show activity indicator. You just dont need to add or remove any code by yourself to get this feature works. Just call loadImageWithURL.
I think u are using asynimageview classs, In that by default you will get the loader in the cell itself .
AysncImageView already has a loader.
You won't see it if your background is black since it loads the default activity indicator.
So, just set the activityIndicatorStyle property for your AsyncImageView object based on your background.
In my case, my background was black, so I used the following code :
asyncImgView.activityIndicatorStyle = UIActivityIndicatorViewStyleWhite;

Navigating to a different view - pushViewController

I have a tableview, and when i click on a row, it navigates to another view; The code for the navigation part is shown below;
ShowImageController *showImageController = [[HowItWorksViewController alloc] initWithNibName:nil bundle:nil];
[self.navigationController pushViewController:showImageController animated:YES];
The other view contains an image, i have added the image to its viewDidLoad. and here's the code for that
UIImageView *imageView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"hello.png"]];
[imageView setFrame:CGRectMake(o, o, 200, 300)];
[[self view] addSubview:imageView ];
The problem is When i click on the row it takes a long time (extremely slow), to navigate to the other screen.
note: Rows which didn't have an image in the other view navigated well with no issue. Why is this happening ? and how can i fix it ?
Try loading the images in a asynk task or nsoperationqueue :)
Definitely sounds like the images are big and therefore taking a while to load. I suggest you either use smaller images or if you have no control over them you might want to try loading the images in the background. Here is some code to get you started with loading them in the background:
- (void)decodeImageInBackgroundThread:(UIImage*)decodedImage forImageView:(UIImageView*)imageView {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
CGImageRef originalImage = [decodedImage CGImage];
CFDataRef imageData = CGDataProviderCopyData(CGImageGetDataProvider(originalImage));
CGDataProviderRef imageDataProvider = CGDataProviderCreateWithCFData(imageData);
if (imageData != NULL) {
CFRelease(imageData);
}
CGImageRef image = CGImageCreate(CGImageGetWidth(originalImage),
CGImageGetHeight(originalImage),
CGImageGetBitsPerComponent(originalImage),
CGImageGetBitsPerPixel(originalImage),
CGImageGetBytesPerRow(originalImage),
CGImageGetColorSpace(originalImage),
CGImageGetBitmapInfo(originalImage),
imageDataProvider,
CGImageGetDecode(originalImage),
CGImageGetShouldInterpolate(originalImage),
CGImageGetRenderingIntent(originalImage));
if (imageDataProvider != NULL) {
CGDataProviderRelease(imageDataProvider);
}
dispatch_async(dispatch_get_main_queue(), ^{
[imageView setImage:[UIImage imageWithCGImage:image]];
CGImageRelease(image);
});
});
}
Which you can then use like this:
- (void)viewDidLoad {
...
UIImage *image = [UIImage imageNamed:#"hello.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:nil];
[imageView setFrame:CGRectMake(0.0f, 0.0f, 200.0f, 300.0f)];
[[self view] addSubview:imageView];
[self decodeImageInBackgroundThread:image forImageView:imageView];
}

how to pushViewController to another view with images in a scrollview

I have a scrollview of images, I will like to tab them and will pushed to another view.
once i tab on the image, the whole view should push to another view.
From this View to another view
Detail view
Sorry for not asking the question clearly.
my scrollview
-(void)pictureScrolling
{
//init scrollview in location on screen
scrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 100, 320, 290)];
scrollview.backgroundColor = [UIColor redColor];
//pass image filenames
NSMutableArray *fileNames = nearbyFrog.imageFiles; //[[[NSMutableArray alloc] init] autorelease];
//setup the array of uiimageviews
NSMutableArray *imgArray = [[NSMutableArray alloc] init];
UIImageView *imageView;
//loop through the array imgNames to add file names to imgArray
for (NSString *imageName in fileNames) {
imageView = [[UIImageView alloc] init];
imageView.image = [UIImage imageNamed:imageName];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[imgArray addObject:imageView];
[imageView release];
}
CGSize pageSize = scrollview.frame.size;
NSUInteger page = 0;
for (UIView *viewForScrollView in imgArray) {
[scrollview addSubview:viewForScrollView];
viewForScrollView.frame = CGRectMake(pageSize.width * page++ +10, 0, pageSize.width -20 , pageSize.height);
// making use of the scrollView's frame size (pageSize) so we need to;
// +10 to left offset of image pos (1/2 the gap)
// -20 for UIImageView's width (to leave 10 gap at left and right)
}
//add scroll view to view
[self.view addSubview:scrollview];
scrollview.contentSize = CGSizeMake(pageSize.width * [imgArray count], pageSize.height);
//scrollview.contentSize = CGSizeMake(320 *viewcount + 20, 290 );
scrollview.showsHorizontalScrollIndicator =NO;
[scrollview setPagingEnabled:YES];
scrollview.delegate =self;
//paging function for scrollview
CGRect frame = [[UIScreen mainScreen] applicationFrame];
self.pageControl = [[[UIPageControl alloc] initWithFrame:CGRectMake(0, 100, 100, 50)] autorelease];
self.pageControl.center = CGPointMake(frame.size.width/2, frame.size.height-60);
self.pageControl.numberOfPages = [fileNames count];
[self.view addSubview:self.pageControl];
//handle Touch Even
[pageControl addTarget:self action:#selector(changePage:) forControlEvents:UIControlEventValueChanged];
[imgArray release];
}
anybody knows how to do it or can show me a tutorial?
Thanks
I think this is the best way to implement it
Create your own Custom UIImageView class. This is required to store an additional property which will help you identify which image for clicked.
Create a delegate for that class which is called with the single tap event is raised in the UIImageView
Add the Images inside the scrollview using this custom class. The delegate of this class will tell you which image was tapped. You can use this to push a new view controller passing the image details (if necessary).
You can find some sample code in the ThumbImageView class in the scrollviewSuite sample
http://developer.apple.com/library/ios/#samplecode/ScrollViewSuite/Introduction/Intro.html#//apple_ref/doc/uid/DTS40008904-Intro-DontLinkElementID_2

How to remove overlapping uiimageview?

I tried to change the image in the imageview but I can't seem to do that.
My code shown below creates a new subview for each image to display. However, the images just overlap and shows the overlapped images at the end which is not supposed to be.
.m:
for (int i = 0; i < [imageArr count]; i++) {
NSArray *imageNameArr = [[imageArr objectAtIndex:i] componentsSeparatedByString:#"."];
check=line;
NSString *msg = [textView.text stringByAppendingString:[NSString stringWithFormat:#"Opening image: %#\n",[imageArr objectAtIndex:i]]];
[textView performSelectorOnMainThread:#selector(setText:) withObject:msg waitUntilDone:NO];
line=line+1;
NSString *imagePath = [NSString stringWithFormat:#"%#/%#",jName,[imageArr objectAtIndex:i]];
NSString *imageFile = [NSHomeDirectory() stringByAppendingPathComponent:imagePath];
NSLog(#"------------------------------");
NSLog(#"ImageFile: %#\n",imageFile);
NSLog(#"Interger value: %i\n",i);
UIImage *myImage = [UIImage imageWithContentsOfFile:imageFile];
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
imageView.contentMode = UIViewContentModeScaleAspectFit;
[scrollView addSubview:imageView];
[imageView release];
.....
.....
}
How to show the images individually, without overlapping?
put this line out of for loop:
UIImageView *imageView = [[UIImageView alloc] initWithImage:myImage];
[scrollView addSubview:imageView];
and use it like:
UIImageView *imageView = [[UIImageView alloc] init];
[scrollView addSubview:imageView];
and use:
[imageView setImage:[UIImage imageWithContentsOfFile:fullImgNm]];
Inside for loop.
You create the imageview out of loop and change the source(Image) for that imageview inside the loop.
You do this before loop starts,
UIImageView *imageView = [[UIImageView alloc] init];
[scrollView addSubview:imageView];
and add the image like this inside the loop,
[imageView setImage:[UIImage imageWithContentsOfFile:imageFile]];

Custom back button disappears after setting navigation bar background image

I'm using the following categories code to change
the background image of the navigation bar
#import <Foundation/Foundation.h>
#interface UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image;
- (void) clearBackgroundImage;
#end
#import "UINavigationBar+CustomImage.h"
#implementation UINavigationBar (CustomImage)
- (void) setBackgroundImage:(UIImage*)image {
if (image == NULL) return;
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
imageView.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
[self insertSubview:imageView atIndex:0];
[imageView release];
}
- (void) clearBackgroundImage {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSArray *mySubviews = [self subviews];
for (int i = [mySubviews count] - 1; i >= 0; i--)
{
if ([[mySubviews objectAtIndex:i] isMemberOfClass:[UIImageView class]])
{
[[mySubviews objectAtIndex:i] removeFromSuperview];
return;
}
}
[pool release];
}
#end
And i'm using the following code to generate the custom back button
in my view
UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
[btnBack addTarget:self action:#selector(goBack) forControlEvents:UIControlEventTouchUpInside];
[btnBack setImage:[UIImage imageNamed:#"back.png"] forState:UIControlStateNormal];
UIBarButtonItem *barBtnBack = [[UIBarButtonItem alloc] initWithCustomView:btnBack];
self.navigationItem.leftBarButtonItem = barBtnBack;
[btnBack release];
[barBtnBack release];
But the button most of the time is hidden under the bg image
and some times it randomly appears.
Why is this happening? I'm not sure what's the problem the image is inserted at index 0
so as I understand it is supposed to be behind all the time.
Please help.
Try the following code to change background of the navigation bar in the class where you are loading the navigation bar.
#interface UINavigationBar (MyCustomNavBar)
#end
#implementation UINavigationBar (MyCustomNavBar)
- (void) drawRect:(CGRect)rect
{
UIImage *barImage = [UIImage imageNamed:#"image.png" ];
[barImage drawInRect:rect];
}
#end
Using the method Praveen S suggested you could have a global variable for the next background image name and set it in your viewDidLoad method, then in your draw rect method use the imageName stored in the variable rather than hardcoding it in the draw rect.
You should try creating the button after adding the image.