how to resize the button image in iphone - iphone

im new in iphone.now im developing button image view in iphone.here images are images displaying large size i want to resize the images. that means images are displayed like medium size. i implement code like this.
images = [[NSMutableArray alloc]init];
[images addObject:[UIImage imageNamed:#"bearlarge.jpg"]];
[images addObject:[UIImage imageNamed:#"bufflo_large.jpg"]];
[images addObject:[UIImage imageNamed:#"camel_large.jpg"]];
UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
int row = 0;
int column = 0;
for(int i = 0; i < images.count; ++i) {
// UIImage *thumb = [images objectAtIndex:i];
UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(column*105+14, row*105+10, 50,50);
[button setImage:[images objectAtIndex:i] forState:UIControlStateNormal];
[button addTarget:self
action:#selector(buttonClicked:)
forControlEvents:UIControlEventTouchUpInside];
button.tag = i;
[view addSubview:button];
if (column == 2) {
column = 0;
row++;
} else {
column++;
}
}
//[view setContentSize:CGSizeMake(320, (row+1) * 80 + 10)];
self.view = view;
[view release];
can any one plz send me code for how to resize the button images in iphone.
Thank you in advançe.

You could create this category for UIImage:
- (UIImage *)rescaleImageToSize:(CGSize)size {
CGRect rect = CGRectMake(0.0, 0.0, size.width, size.height);
UIGraphicsBeginImageContext(rect.size);
[self drawInRect:rect]; // scales image to rect
UIImage *resImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return resImage;
}

Better add a UIImageView over the button. So that you can easily change the frame size.
CODE
UIButton *imageBut=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
UIImageView *img=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
img.userInteractionEnabled=NO;
[imageBut addSubview:img];
[self.view addSubview:imageBut];
[imageBut release];
[img release];
Or else, use
[button setBackgroundImage:YourImage];

setImage will set the image with original size in which you are included that into your project.
setBackgroundImage will resize the original image.
[button setBackgroundImage:[images objectAtIndex:i] forState:UIControlStateNormal];

-(void)scaleImage:(id)sender
{
if([(UIPinchGestureRecognizer*)sender state] == UIGestureRecognizerStateEnded)
{
lastScale = 1.0;
return;
}
CGFloat scale = 1.0 - (lastScale - [(UIPinchGestureRecognizer*)sender scale]);
CGAffineTransform currentTransform = [(UIPinchGestureRecognizer*)sender view].transform;
CGAffineTransform newTransform = CGAffineTransformScale(currentTransform, scale, scale);
[[(UIPinchGestureRecognizer*)sender view] setTransform:newTransform];
lastScale = [(UIPinchGestureRecognizer*)sender scale];
}

Related

iphone vs ipad simulator image size not behaving as it should

buttonTapped method check if it is an small iphone, normal iphone or ipad. Set the image name and size accordingly. There is no problem with it, works as expected.
When clicked on the "pressedClassicButton" it reloads some data in other views and changes images of some other uiviews. it should not touch imageView in any way. The data it changes are not connected to imageView also.
But somehow when i call the "pressedClassicButton" method, it starts ignoring my specified ipad frame sizes and sets the imageView size as specified on the storyboard constraints. This problem only happens in ipad.
The constraints are: 1:1 ratio, 20px to left right and top.
- (IBAction)pressedClassicButton:(id)sender {
[Flurry logEvent:#"Pressed->SelectPage->Classic"];
[self toggleButton:sender];
self.currentArray = self.classicArray;
[self.swipeView reloadData];
}
-(void)toggleButton:(UIButton *)button{
UIImage *inactiveButton = [UIImage imageNamed:#"fruitify_tab_inactive.png"];
UIImage *activeButton = [UIImage imageNamed:#"fruitify_tab_active.png"];
[self.buttonClassicOut setBackgroundImage:inactiveButton forState:UIControlStateNormal];
[self.buttonGroupOut setBackgroundImage:inactiveButton forState:UIControlStateNormal];
[self.buttonSpecialOut setBackgroundImage:inactiveButton forState:UIControlStateNormal];
[self.buttonTropicalOut setBackgroundImage:inactiveButton forState:UIControlStateNormal];
[button setBackgroundImage:activeButton forState:UIControlStateNormal];
}
- (void)buttonTapped:(UIButton *)sender
{
int clicked = (int)sender.tag;
self.lastChoice = clicked;
NSString *str = self.currentArray[clicked][3];
for (UIView *subView in self.imageView.subviews)
{
if (subView.tag < 120 && subView.tag > 100)
{
[subView removeFromSuperview];
}
}
NSString *machineName = [[NSString alloc] initWithString:[MasterClass MachineName]];
if ([machineName rangeOfString:#"iPad"].location != NSNotFound) {
NSLog(#"ipad");
self.imageView.frame = CGRectMake(120.0, 80.0, 520, 520);
} else if ([machineName rangeOfString:#"iPhone3"].location != NSNotFound) {
self.imageView.frame = CGRectMake(50.0, 70.0, 220, 220);
NSLog(#"iphone3-4");
} else if ([machineName rangeOfString:#"iPod"].location != NSNotFound) {
self.imageView.frame = CGRectMake(50.0, 70.0, 220, 220);;
NSLog(#"iphone3-4");
}
else{
self.imageView.frame = CGRectMake(20.0, 82.0, 280, 280);
NSLog(#"iphone5+");
}
self.imageView.image = [UIImage imageNamed:self.currentArray[clicked][4]];
[self.imageView setUserInteractionEnabled:YES];
float realImageSize = self.imageView.image.size.height;
float viewBoundSize = self.imageView.bounds.size.height;
float sizeDifference = realImageSize / viewBoundSize;
if (![str isEqual: #"group"]) {
CGPoint eye = CGPointMake([self.currentArray[clicked][8] floatValue] / sizeDifference, [self.currentArray[clicked][9] floatValue] / sizeDifference);
CGPoint mouth = CGPointMake([self.currentArray[clicked][10] floatValue] / sizeDifference, [self.currentArray[clicked][11] floatValue] / sizeDifference);
CGPoint center = CGPointMake( (eye.x + mouth.x)/2 , (eye.y + mouth.y)/2 );
CGFloat xDist = (eye.x - mouth.x);
CGFloat yDist = (eye.y - mouth.y);
CGFloat faceSize = sqrt((xDist * xDist) + (yDist * yDist));
UIImage *tapFace = [UIImage imageNamed:#"fruitify_face_button.png"];
CGRect newBound = CGRectMake(center.x - faceSize, center.y - faceSize, faceSize*2, faceSize*2);
UIButton *tapButton = (UIButton *)self.imageView;
tapButton = [UIButton buttonWithType:UIButtonTypeCustom];
[tapButton setFrame:newBound];
[tapButton setBackgroundImage:tapFace forState:UIControlStateNormal];
tapButton.userInteractionEnabled = YES;
tapButton.tag = 113;
tapButton.enabled = YES;
[tapButton addTarget:self action:#selector(tapHereTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.imageView addSubview:tapButton];
}else if([str isEqual:#"group"]){
int faceCount = [self.currentArray[clicked][8] count];
for (int i = 0; i < faceCount; i++) {
CGPoint eye = CGPointMake([self.currentArray[clicked][8][i] floatValue] / sizeDifference, [self.currentArray[clicked][9][i] floatValue] / sizeDifference);
CGPoint mouth = CGPointMake([self.currentArray[clicked][10][i] floatValue] / sizeDifference, [self.currentArray[clicked][11][i] floatValue] / sizeDifference);
CGPoint center = CGPointMake( (eye.x + mouth.x)/2 , (eye.y + mouth.y)/2 );
CGFloat xDist = (eye.x - mouth.x);
CGFloat yDist = (eye.y - mouth.y);
CGFloat faceSize = sqrt((xDist * xDist) + (yDist * yDist));
UIImage *tapFace = [UIImage imageNamed:#"fruitify_face_button.png"];
CGRect newBound = CGRectMake(center.x - faceSize, center.y - faceSize, faceSize*2, faceSize*2);
UIButton *tapButton = (UIButton *)self.imageView;
tapButton = [UIButton buttonWithType:UIButtonTypeCustom];
[tapButton setFrame:newBound];
[tapButton setBackgroundImage:tapFace forState:UIControlStateNormal];
tapButton.userInteractionEnabled = YES;
tapButton.tag = 113 + i;
tapButton.enabled = YES;
[tapButton addTarget:self action:#selector(tapHereTapped:) forControlEvents:UIControlEventTouchUpInside];
[self.imageView addSubview:tapButton];
}
}
}
Unexpected things happen when you use constraints and try to set frames as well. Try setting the sizes of your views by altering their constraints instead. You add them as properties from your storyboard by ctrl click drag like you do when hooking up a button.

UIImageView doesn't follow origin.x position

I am trying to add set of imageviews on a UIScrollView. My problem is that the imageviews are overlapping with each other even though I increase the x value. What's also weird is that this problem is only for devices with ios 4.2.1, but works on simulator 4.2 and other device ios.
Here is my code:
- (void)addScrollView {
[self setImages];
scrollView = [[UIScrollView alloc] initWithFrame:self.frame];
scrollView.delegate = self;
[scrollView setBackgroundColor:[UIColor blackColor]];
[scrollView setCanCancelContentTouches:NO];
scrollView.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView.clipsToBounds = YES;
scrollView.scrollEnabled = YES;
scrollView.pagingEnabled = YES;
[self addSubview:scrollView];
NSUInteger nimages;
CGFloat cx = 0;
for (nimages = 1; nimages < [imagesArray count] ; nimages++) {
UIImage *image = [UIImage imageNamed:[imagesArray objectAtIndex:nimages]];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
CGRect rect = imageView.frame;
rect.origin.x = cx;
rect.origin.y = 0;
rect.size.width = 320;
rect.size.height = 480;
imageView.frame = rect;
[scrollView addSubview:imageView];
[imageView release];
cx += rect.size.width;
}
[scrollView setContentSize:CGSizeMake(cx, [scrollView bounds].size.height)];
}
Called from here:
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self addScrollView];
UIImage *handImg;
UIImageView *longhand = [[UIImageView alloc] init];
minuteHand = [[UIView alloc] initWithFrame:CGRectMake(0, 55, 320, 480)];
handImg = [UIImage imageNamed:#"clock_long_hand.png"];
longhand.image = handImg;
/************** TRY COMMENT OUT HERE **************/
longhand.frame = CGRectMake(155 - (handImg.size.width / 2), 240 - handImg.size.height, handImg.size.width, handImg.size.height);
[minuteHand addSubview:longhand];
[self addSubview:minuteHand];
/************** END COMMENT OUT HERE **************/
[longhand release];
}
return self;
}
UPDATE:
This code is in a UIView subclass which is why I use [self...] instead of [self.view...].
I tried experimenting and found that when I comment out the indicated parts, the scrollview works fine. But when it is included, this is when the imageviews are overlapped.
I know that the scrollview's content size is correct because its indicator continues to scroll, with just a plain black background.
I am really confused why this works on some ios and not on others. Hope you can help.
This might have something to do with autoresizing mask. The width actual images, I mean .png files is bigger than 320, right?

Save and load a UIScrollView position

Im creating an app that uses a UIScrollView that scrolls through images and a segmented control that loads a new view and allows a new layer of images (bit like Photoshop layering) - For some reason when I click back on the layer, it remembers the position but creates a new layer.... How can I stop this from happening, so once a layer has been selected and an image chosen, when the user returns it goes to the last loaded position?
Also, as a side thing... I cannot use my gesture recognition or UIAlertView when the UIScrollView is loaded? Does anyone know why?
Here is my code.... And thanks in advance:)
- layerControl:(NSInteger)index
{
UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSInteger viewCount = 15;
for (int i = 0; i < viewCount; i++) {
CGFloat yOrigin = i * self.view.frame.size.width;
UIImageView *filterViewOverlay = [[UIImageView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
[filterViewOverlay setImage:[filterManager objectAtIndex:i]];
[scroll addSubview:filterViewOverlay];
[filterViewOverlay release];
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * viewCount, self.view.frame.size.height);
[self.view addSubview:scroll];
[scroll release];
switch (index)
{
case 0: scroll = self.scroll1;
case 1: scroll = self.scroll2;
case 2: scroll = self.scroll3;
case 4: scroll = self.scroll4;
case 5: scroll = self.scroll5;
}
/* if (scroll == nil)
{
[[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
scroll.pagingEnabled = YES;
NSInteger viewCount = 15;
for (int i = 0; i < viewCount; i++) {
CGFloat yOrigin = i * self.view.frame.size.width;
UIImageView *filterViewOverlay = [[UIImageView alloc] initWithFrame:CGRectMake(yOrigin, 0, self.view.frame.size.width, self.view.frame.size.height)];
[filterViewOverlay setImage:[filterManager objectAtIndex:i]];
[scroll addSubview:filterViewOverlay];
//[filterViewOverlay release];
}
scroll.contentSize = CGSizeMake(self.view.frame.size.width * viewCount, self.view.frame.size.height);
[self.view addSubview:scroll];
[scroll autorelease]; */
}
}
//Method to add a filter to the page
- (void)addFilter:(id)sender
{
UISegmentedControl *filterController = (UISegmentedControl *)sender;
[self layerControl:[filterController selectedSegmentIndex]];
}
- (UIImage*)saveImages
{
UIImage *image = [UIImage imageNamed:#"UrbanPhoto##1"];
UIGraphicsBeginImageContext(self.view.bounds.size);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
Try saving the value of UIScrollView.contentOffset before the user action, and then restoring that value after the action is completed.

iphone: how to add text above and below the image in the scrollvew?

I would like to add a page number above the image such as "1 of 50" and description of the image below the image in the scrollview.
I have looked at this LINK but still couldn't figure out how to make it happen.
here is my sample code of the images scrollview. Im trying to find a sample that can add text and scroll with the images
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"images%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView1 addSubview:imageView];
[imageView release];
}
UPDATE:
const CGFloat kScrollObjHeight = 320;
const CGFloat kScrollObjWidth = 280.0;
const NSUInteger kNumImages = 50;
- (void)layoutScrollImages
{
UIImageView *view = nil;
NSArray *subviews = [scrollView1 subviews];
// reposition all image subviews in a horizontal serial fashion
CGFloat curXLoc = 0;
for (view in subviews)
{
if ([view isKindOfClass:[UIImageView class]] && view.tag > 0)
{
CGRect frame = view.frame;
frame.origin = CGPointMake(curXLoc, 0);
view.frame = frame;
curXLoc += (kScrollObjWidth);
}
}
- (void)viewDidLoad {
self.view.backgroundColor = [UIColor viewFlipsideBackgroundColor];
// 1. setup the scrollview for multiple images and add it to the view controller
//
// note: the following can be done in Interface Builder, but we show this in code for clarity
[scrollView1 setBackgroundColor:[UIColor blackColor]];
[scrollView1 setCanCancelContentTouches:NO];
scrollView1.indicatorStyle = UIScrollViewIndicatorStyleWhite;
scrollView1.clipsToBounds = YES; // default is NO, we want to restrict drawing within our scrollview
scrollView1.scrollEnabled = YES;
// pagingEnabled property default is NO, if set the scroller will stop or snap at each photo
// if you want free-flowing scroll, don't set this property.
scrollView1.pagingEnabled = YES;
// load all the images from our bundle and add them to the scroll view
NSUInteger i;
for (i = 1; i <= kNumImages; i++)
{
NSString *imageName = [NSString stringWithFormat:#"creative%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// setup each frame to a default height and width, it will be properly placed when we call "updateScrollList"
CGRect rect = imageView.frame;
rect.size.height = kScrollObjHeight;
rect.size.width = kScrollObjWidth;
imageView.frame = rect;
imageView.tag = i; // tag our images for later use when we place them in serial fashion
[scrollView1 addSubview:imageView];
[imageView release];
}
[self layoutScrollImages];
I wanted to put this but unable to find the correct position or right offset to display at the top
UILabel * topLabel = [[UILabel alloc] init];
topLabel.text = [NSString stringWithFormat:#"%d of %d", i, kNumImages];
rect.origin.x = offset;
rect.size.height = 30; // however large you need the label to be
topLabel.frame = rect;
offset += 30;
I would think something like this would work:
float offset = 0;
for (NSUInteger i = 1; i <= kNumImages; i++)
{
// load up the image
NSString *imageName = [NSString stringWithFormat:#"images%d.jpg", i];
UIImage *image = [UIImage imageNamed:imageName];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
// image.size is important here and used to determine placement
CGRect rect = imageView.frame;
rect.size = image.size;
// create top label, just basic will need to configure other settings like font
UILabel * topLabel = [[UILabel alloc] init];
topLabel.text = [NSString stringWithFormat:#"%d of %d", i, kNumImages];
rect.origin.x = offset;
rect.size.height = 30; // however large you need the label to be
topLabel.frame = rect;
offset += 30; // adding the label height
// set image frame since we now know the location below top label
rect.size = image.size;
rect.origin.x += offset;
imageView.frame = rect;
imageView.tag = i;
offset += image.size.height; // adding image height
// add bottom label below image
UILabel * bottomLabel = [[UILabel alloc] init];
bottomLabel.text = imageName; // just a sample description
rect.origin.x += offset;
rect.size.height = 30; // however large you need the label to be
bottomLabel.frame = rect;
offset += 30; // adding the label height
[scrollView1 addSubview:topLabel];
[scrollView1 addSubview:imageView];
[scrollView1 addSubview:bottomLabel];
[imageView release];
[topLabel release];
[bottomLabel release];
offset += 20; // arbitrary spacing between images
}

How can I make a UIScrollView image gallery? (iPhone SDK)

I've been struggling with trying to get my UIImageView to change its image when the UIScrollView is scrolled, kind of like the Photos.app.
Here's my code:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
if (scrollView.contentOffset.x > 296){
self.currentDBNum++;
self.currentDoorbell = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[[self.doorbells objectAtIndex:currentDBNum] objectForKey:#"Image"] ofType:#"jpg"]];
self.doorbellPic.image = currentDoorbell;
self.currentSoundPath = [[NSBundle mainBundle] pathForResource:[[doorbells objectAtIndex:currentDBNum] objectForKey:#"Sound"] ofType:#"caf"];
}
}
Any hints? Thanks. (The images have a width of 296.)
There are two ways that accomplish your task:
Try to learn Three20 TTPhotoViewController that will do exactly the same as the photo.app that you see in your iphone.
If you want to do it yourself then from my experience, you have to add multiple UIImageView with the correct position (x,y,width,height) to the UIScrollView. Remember to initialize the scroll view with the right content-size so that it's scrollable. An example: image1 is (0,0,320,480), image2 is (320,0,320,480), image3 is (640,0,320,480), etc... then your scroll view content size will be the x's value of the last item + the width of the last item.
Antohny,
I do not have my own source code right with me, but I can suggest you the following link:
http://github.com/andreyvit/ScrollingMadness
I think it will give you an idea so you can implement it without hitting the corners.
you can do it by using following code:
UIImageView *tempImageView ;
int initialXPos = 0;
int initialYPos = 30;
view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 800)];
int arraycounter=0;
for (int i=0; i<numrows; i++)
{
for (int j=0; j<numImagesPerColumn; j++)
{
NSURL *url=[NSURL URLWithString:[aPhoto.childphotos objectAtIndex:arraycounter]];
UIImage *image1;
CGRect image1Frame;
image1 = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
image1Frame = CGRectMake(initialXPos,initialYPos, 80, 80);
tempImageView = [[UIImageView alloc] initWithFrame:image1Frame];
tempImageView.image=image1;
tempImageView.tag = 0;
initialXPos = initialXPos + 80 + 4;
[view addSubview:tempImageView];
arraycounter=arraycounter+1;
}
initialXPos=0;
initialYPos = initialYPos + 86;
}
scrollView.maximumZoomScale = 4.0;
scrollView.minimumZoomScale = 0.75;
scrollView.clipsToBounds = YES;
scrollView.delegate = self;
[scrollView addSubview:view];
[scrollView addSubview:title];
[scrollView addSubview:des];
[self.view addSubview:scrollView ];
u try this
-(void)getButtonRowSize:(int)_rowsize Count:(int)_count
{
[scrollView setFrame:CGRectMake(0, 0, 320, 480)];
[scrollView setContentSize:CGSizeMake(320,((320-_rowsize*IMAGEGAP)/_rowsize)*(_count/_rowsize +1)+(_count/_rowsize)*IMAGEGAP)];
for(int i=0;i<_count;i++)
{
[scrollView addSubview:[self getButtonRowSize:_rowsize Count:_count currentPos:i]];
}
}
-(UIButton *)getButtonRowSize:(int)_rowsize Count:(int)_count currentPos:(int)_pos
{
UIButton *button=[UIButton buttonWithType:UIButtonTypeCustom];
[button setFrame:CGRectMake((_pos%_rowsize)*((320-(_rowsize+1)*IMAGEGAP)/_rowsize)+(_pos%_rowsize +1)*IMAGEGAP,(_pos/_rowsize)*((320-(_rowsize+1)*IMAGEGAP)/_rowsize)+(_pos/_rowsize +1)*IMAGEGAP,((320-(_rowsize+1)*IMAGEGAP)/_rowsize),((320-(_rowsize+1)*IMAGEGAP)/_rowsize))];
[button setBackgroundImage:[self resizingImagewithimagename:[UIImage imageNamed:#"add image file name"] Length:((320-(_rowsize+1)*IMAGEGAP)/_rowsize)] forState:UIControlStateNormal];
return button;
}