setting pics as UIImages as instance variables - uiimageview

I have a folder of png's called "cards" in Supporting Files. I'm trying to set a pic as a UIImage instance variable for a object. When i try to NSLog the UIImage i get null.
I don't think I'm accessing the path to the pics correctly, but not sure ????
#import "Deck.h"
#import "Card.h"
#implementation Deck
#synthesize cards;
- (id) init
{
if(self = [super init])
{
cards = [[NSMutableArray alloc] init];
NSInteger aCount, picNum = 0;
for(int suit = 0; suit < 4; suit++)
{
for(int face = 1; face < 14; face++, picNum++)
{
//NSString *path = [[NSBundle mainBundle] bundlePath];
//NSString *imagePath = [path stringByAppendingPathComponent: [NSString stringWithFormat:#"/cards/card_%d.png",picNum]];
NSString *fileName = [NSString stringWithFormat:#"card_%d", picNum];
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:#"png"inDirectory:#"/cards"];
NSLog(#"%#", path);
UIImage *output = [UIImage imageNamed:path];
//NSLog(#"%#", output);
Card *card = [[Card alloc] initWithFaceValue:(NSInteger)face
countValue:(NSInteger)aCount
suit:(Suit)suit
cardImage:(UIImage *)output];
[cards addObject:card];
}
}
}
return self;
}
}
#end

The conceptually better approach would be to use the method of NSBundle which was specifically designed for working with subdirectories:
NSString *fileName = [NSString stringWithFormat:#"card_%d", picNum];
NSString *path = [[NSBundle mainBundle] pathForResource:fileName
ofType:#"png"
inDirectory:#"cards"];

Related

access an UIImage instance variable and display it in UIImageView

I'm trying to access an UIImage instance variable and display it in UIImageView. When I try to NSLog the path I get null. I can manually display a pic through the IB, but I want to do this strictly through code
#import "Deck.h"
#import "Card.h"
#implementation Deck
#synthesize cards;
- (id) init
{
if(self = [super init])
{
cards = [[NSMutableArray alloc] init];
NSInteger aCount, picNum = 0;
for(int suit = 0; suit < 4; suit++)
{
for(int face = 1; face < 14; face++, picNum++)
{
NSString *fileName = [NSString stringWithFormat:#"card_%d", picNum];
NSString *path = [[NSBundle mainBundle] pathForResource:fileName
ofType:#"png"inDirectory:#"/cards"];
NSLog(#"%#", path); //outputs correctly
UIImage *output = [UIImage imageNamed:path];
NSLog(#"%#", output); //outputs null
Card *card = [[Card alloc] initWithFaceValue:(NSInteger)face
countValue:(NSInteger)aCount
suit:(Suit)suit
cardImage:(UIImage *)output];
[cards addObject:card];
}
}
}
return self;
}
I've added a link to show where the pics are found
Link
You don't have to include all the path to the image, if you just put the name, Xcode will automatically look for it.

XCode - UIWebView Not Loading

I have two local .html files in the Resources folder. I'm trying to load them the following way, but only the final page loads. What am I doing wrong?
File = please_wait.html
This one does not work.
NSError *error;
NSString* path = [[NSBundle mainBundle] pathForResource:#"please_wait" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
//Big "do-while" loop here. It works fine so I omitted it.
File = update_graph.html
This one does not work
path = [[NSBundle mainBundle] pathForResource:#"update_graph" ofType:#"html"];
htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
//Lots of code removed. All works correctly and doesn't touch webview
This last one works perfectly. Google displays.
string = #"http://google.com";
NSURL *url = [NSURL URLWithString: string];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
It appears from your comment that your UIWebView loads just fine, but it does not get a chance to refresh itself on the screen until you exit your method. It is not enough to set a break point inside the method and wait for the view to load: you must exit the method before iOS realizes that it needs to call UIWebView's drawRect method.
To fix this, split your method in three parts, A B and C, and set UIWebView's delegate in A to invoke B on webViewDidFinishLoad:, and the delegate in B to call C.
Here is how to implement this: start with a delegate that can call a selector when the loading has completed:
#interface GoToNext : NSObject <UIWebViewDelegate> {
id __weak target;
SEL next;
}
-(id)initWithTarget:(id)target andNext:(SEL)next;
-(void)webViewDidFinishLoad:(UIWebView *)webView;
#end
#implementation GoNext
-(id)initWithTarget:(id)_target andNext:(SEL)_next {
self = [super init];
if (self) {
target = _target;
next = _next;
}
return self;
}
-(void)webViewDidFinishLoad:(UIWebView *)webView {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
[target performSelector:next];
#pragma clang diagnostic pop
}
#end
Now split your method into three parts - loading the first page, loading the second page, and loading the third page:
-(void)loadPleaseWait {
NSError *error;
NSString* path = [[NSBundle mainBundle] pathForResource:#"please_wait" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
webView.delegate = [[GoToNext alloc] initWithTarget:self andNext:#selector(loadUpdateGraph)];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
// big do-while loop
}
-(void)loadUpdateGraph {
NSError *error;
NSString* path = [[NSBundle mainBundle] pathForResource:#"update_graph" ofType:#"html"];
NSString* htmlString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
webView.delegate = [[GoToNext alloc] initWithTarget:self andNext:#selector(loadGoogle)];
[webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:path]];
// Lots of code removed
}
-(void)loadGoogle {
string = #"http://google.com";
NSURL *url = [NSURL URLWithString: string];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
}

How to add a jpg or png image to an UIImage and then display in a UIImageView?

UIImage *img = [[UIImage alloc] initWithContentsOfFile:#"contactHeader.png"];
_headersView = [[UIImageView alloc] initWithImage:img];
I have already hooked up the connections for the UIImageView (_headersView) in IB. The image I want to load is in my project tree structure as well.
Am I creating the UIImage the right way?
If the file is in your bundle you can just use
UIImage *img = [UIImage imageNamed:#"contactHeader"];
_headersView = [[UIImageView alloc] initWithImage:img];
If the image is in your documents directory you can use
// Get the path to your documents directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// Add the file to the end of the documents path
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:#"contactHeader.png"];
UIImage *img = [[UIImage alloc] imageWithContentsOfFile:filePath];
_headersView = [[UIImageView alloc] initWithImage:img];
[img release]; img = nil;
try this
-(NSString *)getPath:(NSString *)filename
{
self.path = [[NSBundle mainBundle]pathForResource:filename ofType:#"png"];
return path;
path = nil;
}
self.youImageView.image = [UIImage imageWithContentsOfFile:[self getPath:#"123"]];

desktop wallpaper [duplicate]

I am trying to change the desktop image; the procedure I've come up with is below. The first time this code is run, the resized image is displayed on screen as wallpaper, but the next time there is no reaction. What am I doing wrong?
-(IBAction)click:(id)sender
{
NSData *sourceData;
NSError *error;
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
screenArray = [NSScreen screens];
screenCount = [screenArray count];
unsigned index = 0;
for (index; index < screenCount; index++)
{
screenz = [screenArray objectAtIndex: index];
screenRect = [screenz visibleFrame];
}
NSLog(#"%fx%f",screenRect.size.width, screenRect.size.height);
arrCatDetails = [strCatDetails componentsSeparatedByString:appDelegate.strColDelimiter];
NSString *imageURL = [NSString stringWithFormat:#"upload/product/image/%#_%#_%d.jpg",[arrCatDetails objectAtIndex:0],appDelegate.str104by157Name,iSelectedImgIndex];
NSString *ima = [imageURL lastPathComponent];
NSString *str = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *dataFilePath = [str stringByAppendingPathComponent:ima];
NSString *imagePath = [NSString stringWithFormat:#"file://localhost%#",dataFilePath];
NSURL *url = [[NSURL alloc] init];
url = [NSURL URLWithString:imagePath];
sourceData = [NSData dataWithContentsOfURL:url];
sourceImage = [[NSImage alloc] initWithData: sourceData];
resizedImage = [[NSImage alloc] initWithSize: NSMakeSize(screenRect.size.width, screenRect.size.height)];
NSSize originalSize = [sourceImage size];
[resizedImage lockFocus];
[sourceImage drawInRect: NSMakeRect(0, 0, screenRect.size.width, screenRect.size.height) fromRect: NSMakeRect(0, 0, originalSize.width, originalSize.height) operation: NSCompositeSourceOver fraction: 1.0];
[resizedImage unlockFocus];
NSData *resizedData = [resizedImage TIFFRepresentation];
NSBitmapImageRep* theImageRepresentation = [NSBitmapImageRep imageRepWithData:resizedData];
newimage = #"editwall.jpg";
newFilePath = [str stringByAppendingPathComponent:newimage];
NSData* theImageData = [theImageRepresentation representationUsingType:NSJPEGFileType properties:nil];
[theImageData writeToFile: newFilePath atomically: YES];
if([filemgr fileExistsAtPath:newFilePath] == YES)
{
imagePath1 = [NSString stringWithFormat:#"file://localhost%#",newFilePath];
urlz = [NSURL URLWithString:imagePath1];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:nil, NSWorkspaceDesktopImageFillColorKey, [NSNumber numberWithBool:NO], NSWorkspaceDesktopImageAllowClippingKey, [NSNumber numberWithInteger:NSImageScaleProportionallyUpOrDown], NSWorkspaceDesktopImageScalingKey, nil];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:urlz forScreen:[[NSScreen screens] lastObject] options:options error:&error];
}
else
{
NSLog(#"No");
}
[sourceImage release];
[resizedImage release];
}
Why not try -[NSWorkspace setDesktopImageURL:forScreen:options:error:]? Apple has a sample project called DesktopImage to give you some idea how to use it.
Edit (after reading your code more carefully):
The problem you're having may be because of your call to +[NSDictionary dictionaryWithObjectsAndKeys:] See the nil at the end of the list of arguments? That's how you tell NSDictionary that your argument list is done. You can't put nil in the list, because it will stop reading the list at that point. If you want to specify a key that has no value, you have to use [NSNull null].
An aside: you've got a memory management issue in your code:
// allocates memory for an NSURL
NSURL * url = [[NSURL alloc] init];
// allocates more memory for an NSURL, and leaks
// the earlier allocation
url = [NSURL URLWithString:imagePath];
Just do one or the other:
// If you do it this way, you will have to call
// [url release] later
NSURL * url = [[NSURL alloc] initWithString:imagePath];
// This memory will be released automatically
NSURL * otherUrl = [NSURL URLWithString:imagePath];

xcode may not respond to warning

Can't seem to get rid of a warning. The warning is:
'UIImage' may not respond to '-scaleToSize'
above the #implmentation MyViewController I have this #implementation:
#implementation UIImage (scale)
-(UIImage*)scaleToSize:(CGSize)size
{
UIGraphicsBeginImageContext(size);
[self drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaledImage;
}
#end
Then I have MyViewController implementation
#implementation TodayNewsTableViewController
#synthesize dataList;
......
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MainNewsCellIdentifier = #"MainNewsCellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: MainNewsCellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier: MainNewsCellIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
NSDictionary *stream = (NSDictionary *) [dataList objectAtIndex:row];
NSString *title = [stream valueForKey:#"title"];
if( ! [title isKindOfClass:[NSString class]] )
{
cell.textLabel.text = #"";
}
else
{
cell.textLabel.text = title;
}
cell.textLabel.numberOfLines = 2;
cell.textLabel.font =[UIFont systemFontOfSize:10];
cell.detailTextLabel.numberOfLines = 1;
cell.detailTextLabel.font= [UIFont systemFontOfSize:8];
cell.detailTextLabel.text = [stream valueForKey:#"created"];
NSString *i = [NSString stringWithFormat:#"http://www.mywebsite.co.uk/images/%#", [stream valueForKey:#"image"]];
NSData *imageURL = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:i]];
UIImage *newsImage = [[UIImage alloc] initWithData:imageURL] ;
UIImage *scaledImage = [newsImage scaleToSize:CGSizeMake(50.0f, 50.0f)]; // warning is appearing here.
cell.imageView.image = scaledImage;
[imageURL release];
[newsImage release];
return cell;
}
Thanks for your time in advance.
Frames
To avoid this warning compiler must "see" your custom method declaration. So you should put
#interface UIImage (scale)
-(UIImage*)scaleToSize:(CGSize)size
#end
somewhere - either to corresponding header file, or in the same implementation file if you do not want this method to be accessible outside current file.

Resources