ios : scrollview not displaying images - ios

I am a beginner and I have developed a program having full screen image scrollview which fetches images from database. but I am getting blank(white) images in output. what will be the reason behind that? plz help, my code is:
#interface GalleryImageScrollViewController ()
{
MyDatabase *data;
NSMutableArray *slideImages;
CGPoint gestureStartPoint,currentPosition;
}
-(void)putImageViewsInScrollView:(int) numberOfImageViews;
#end
#implementation GalleryImageScrollViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.FullScreenImageScroller.delegate= self;
[self putImageViewsInScrollView:slideImages.count];
}
-(void) putImageViewsInScrollView:(int)numberOfImageViews
{
data=[MyDatabase new];
slideImages=[data OpenMyDatabase:#"SELECT pic_name FROM interior" :#"pic_name"];
for(int i=0 ;i< numberOfImageViews; i++)
{
UIImageView *fullScreenImageView = [[UIImageView alloc] init];
fullScreenImageView.frame = CGRectMake((WIDTH_OF_IMAGE * i) , 0, WIDTH_OF_IMAGE, HEIGHT_OF_IMAGE);
fullScreenImageView.image = [UIImage imageNamed:[slideImages objectAtIndex:i]];
[self.FullScreenImageScroller addSubview:fullScreenImageView];
}
[self.FullScreenImageScroller setContentSize:CGSizeMake(WIDTH_OF_SCROLL_PAGE * ([slideImages count]), HEIGHT_OF_IMAGE)];
[self.FullScreenImageScroller setContentOffset:CGPointMake(0, 0)];
[self.FullScreenImageScroller scrollRectToVisible:CGRectMake(WIDTH_OF_IMAGE,0,WIDTH_OF_IMAGE,HEIGHT_OF_IMAGE) animated:NO];
}

Try this
#interface GalleryImageScrollViewController ()
{
MyDatabase *data;
NSMutableArray *slideImages;
CGPoint gestureStartPoint,currentPosition;
}
-(void)putImageViewsInScrollView:(int) numberOfImageViews;
#end
#implementation GalleryImageScrollViewController
- (void)viewDidLoad
{
[super viewDidLoad];
slideImages = [[NSArray alloc]init];
data=[[MyDatabase alloc]init];
slideImages=[data OpenMyDatabase:#"SELECT pic_name FROM exterior" :#"pic_name"];
[self putImageViewsInScrollView:slideImages.count];
self.FullScreenImageScroller.delegate=self;
NSLog(#"Array %#",slideImages);
}
-(void) putImageViewsInScrollView:(int)numberOfImageViews
{
for(int i=0 ;i< numberOfImageViews; i++)
{
UIImageView *fullScreenImageView = [[UIImageView alloc] init];
fullScreenImageView.frame = CGRectMake((WIDTH_OF_IMAGE * i) , 0, WIDTH_OF_IMAGE, HEIGHT_OF_IMAGE);
fullScreenImageView.image = [UIImage imageNamed:[slideImages objectAtIndex:i]];
[self.FullScreenImageScroller addSubview:fullScreenImageView];
}
[self.FullScreenImageScroller setContentSize:CGSizeMake(WIDTH_OF_SCROLL_PAGE * ([slideImages count]), HEIGHT_OF_IMAGE)];
[self.FullScreenImageScroller setContentOffset:CGPointMake(0, 0)];
[self.FullScreenImageScroller scrollRectToVisible:CGRectMake(WIDTH_OF_IMAGE,0,WIDTH_OF_IMAGE,HEIGHT_OF_IMAGE) animated:NO];
}

Related

Programatically adding a Carousel as a SubView

I am trying to add Carousel on the View as follows. As I testing it, nothing happens, it does not even hit any of carousel delegate method.
ViewController.h
#property (nonatomic, strong) iCarousel *carousel;
ViewController.m
carousel = [[iCarousel alloc] initWithFrame:CGRectMake(25, 50, self.view.frame.size.width-50, self.view.frame.size.height-75)];
[self.view addSubview:carousel];
carousel.delegate = self;
carousel.dataSource = self;
self.carousel.type = iCarouselTypeCoverFlow2;
self.items = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
[carouselItems addObject:#(i)];
}
[carousel reloadData];
Replace your code with this
self.carousel = [[iCarousel alloc] initWithFrame:CGRectMake(25, 50, self.view.frame.size.width-50, self.view.frame.size.height-75)];
self.carousel.delegate = self;
self.carousel.dataSource = self;
self.carousel.type = iCarouselTypeCoverFlow2;
[self.view addSubview:self.carousel];
self.items = [NSMutableArray array];
for (int i = 0; i < 100; i++)
{
[carouselItems addObject:#(i)];
}
[self.carousel reloadData];

Loading overlay on collection view

I have a loading view that I insert over the top of a view while it is parsing data from the internet using a separate thread, in this case its on top of a UICollectionView.
For some reason that I cannot understand the loading overlay disappears on its own whist the parsing is still taking place, presenting a blank screen for a second or two. It doesn't seem to happen on UITableViews just on UIcollectionviews. Any help would be appreciated.
Activity overlay.m:
#import "ActivityOverlayController.h
#interface ActivityOverlayController ()
#end
#implementation ActivityOverlayController
-(id)initWithFrame:(CGRect)theFrame {
if (self = [super init]) {
frame = theFrame;
self.view.frame = theFrame;
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(#"%#", #"ActivityOverlayController called");
container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 110, 30)];
activityLabel = [[UILabel alloc] init];
activityLabel.text = NSLocalizedString(#"Loading", #"string1");
activityLabel.textColor = [UIColor lightGrayColor];
activityLabel.font = [UIFont boldSystemFontOfSize:17];
[container addSubview:activityLabel];
activityLabel.frame = CGRectMake(0, 3, 70, 25);
activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
activityIndicator.color = [UIColor blackColor];
activityIndicator.hidesWhenStopped = TRUE;
[activityIndicator startAnimating];
activityIndicator.frame = CGRectMake(80, 0, 30, 30);
[container addSubview:activityIndicator];
[self.view addSubview:container];
container.center = CGPointMake(frame.size.width/2, frame.size.height/2);
self.view.backgroundColor = [UIColor colorWithRed:255 green:255 blue:255 alpha:0.7];
}
-(void)viewWillAppear:(BOOL) animated {
[super viewWillAppear:animated];
}
-(void)viewWillDisappear:(BOOL) animated {
[super viewWillDisappear:animated];
}
-(void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
[activityIndicator stopAnimating];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
#end
Parsing part of collectionViewController.m:
-(void)ParseCollectionView{
[self performSelectorOnMainThread:#selector(showActivityView) withObject:nil waitUntilDone:YES];
CollectionViewImages = [[NSMutableArray alloc]init];
NSData *xmlData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:GalleryTitle]];
cvTBXML = [[TBXML alloc]initWithXMLData:xmlData];
// Obtain root element
TBXMLElement * root = cvTBXML.rootXMLElement;
TBXMLElement * channel = [TBXML childElementNamed:#"channel" parentElement:root];
if (root)
{
TBXMLElement * item = [TBXML childElementNamed:#"item" parentElement:channel];
while (item !=nil)
{
//create new instance of news object
NSObject *Imagetoparse = [[GalleryImage alloc] init];
TBXMLElement * link = [TBXML childElementNamed:#"link" parentElement:item];
NSString *linktext= [TBXML textForElement:link];
[Imagetoparse setValue:linktext forKey:#"link"];
TBXMLElement * thumbnail = [TBXML childElementNamed:#"description" parentElement:item];
NSString *Thumbnailtext= [TBXML textForElement:thumbnail];
Thumbnailtext = [Thumbnailtext substringFromIndex:21];
NSInteger *slength = Thumbnailtext.length -4;
Thumbnailtext = [Thumbnailtext substringToIndex:slength];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Thumbnailtext = [Thumbnailtext stringByReplacingOccurrencesOfString:#"thumb" withString:#"main"];
NSLog(#"Thumnail1 : %#", Thumbnailtext);
NSData *Thumbnailimage = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: Thumbnailtext]];
[Imagetoparse setValue:Thumbnailimage forKey:#"thumbnail"];
[CollectionViewImages addObject:Imagetoparse];
item = [TBXML nextSiblingNamed:#"item" searchFromElement:item];
}
}
[self.collectionView reloadData];
NSLog(#"%#", #"Finished Parse Collection View");
[self performSelectorOnMainThread:#selector(hideActivityView) withObject:nil waitUntilDone:NO];
}
-(void)showActivityView {
if (overlayController == nil) {
overlayController = [[ActivityOverlayController alloc] initWithFrame:(self.view.superview.bounds)];
}
[self.view.superview insertSubview:overlayController.view aboveSubview:self.view];
}
-(void)hideActivityView {
[overlayController.view removeFromSuperview];
}

Fade Effect when Scrolling

I would like to add the fade effect when user scroll my galleryViewController which fetch the data from the server. I could not able to implement the fade effect to my scrollViewController.
Code:
#import "GrillGalleryCollectionViewController.h"
#import "AFNetworking.h"
#interface GrillGalleryCollectionViewController ()
#end
#implementation GrillGalleryCollectionViewController
#synthesize scrollView,pageControl, colors;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// colors=[[NSArray alloc]init];
colors = [[NSArray alloc] init];;
[self getActiveOffers];
// NSArray *colors = [NSArray arrayWithObjects:[UIColor redColor], [UIColor greenColor], [UIColor blueColor], nil];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender {
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
}
- (IBAction)backBtnPressed:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
pageControlBeingUsed = NO;
}
- (void) getActiveOffers {
NSString *string = #"http://znadesign.com/appcenter/api.php?function=get_gallery&customer_id=1";
NSLog(#"%#", string);
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
int total_count = (int)[[responseObject valueForKey:#"total_count"] integerValue];
if (total_count > 0) {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
for (int i = 1; i <= total_count; i++) {
NSString *key = [NSString stringWithFormat:#"%i", i];
id object = [responseObject objectForKey:key];
[array addObject:object];
}
colors = [NSArray arrayWithArray:array];
[self setSizeSliding];
// [myTableView reloadData];
}
else
{
UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:nil
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView2 show];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 4
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"There is no internet connection."
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
// 5
[operation start];
}
-(void) setSizeSliding
{
for (int i = 0; i < colors.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
// UIView *subview = [[UIView alloc] initWithFrame:frame];
// subview.backgroundColor = [colors objectAtIndex:i];
// NSString *imageURLString=[[offersArray objectAtIndex:indexPath.row] valueForKey:#"picture"];
NSString*slidingImage = [[colors objectAtIndex:i] valueForKey:#"picture"];
NSURL *url = [NSURL URLWithString:slidingImage];
NSData *data = [[NSData alloc] initWithContentsOfURL:url];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
UIImageView *slidingImageView = [[UIImageView alloc]initWithFrame:frame];
slidingImageView.image = tmpImage;
[self.scrollView addSubview:slidingImageView];
}
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * colors.count, self.scrollView.frame.size.height);
}
#end
I want to implement the similar fade effect as it is listed below:
[UIView animateWithDuration:2
animations:^{imageView.alpha = 0.0;}
completion:^(BOOL finished){ [imageView removeFromSuperview];}];
You have the code Can you adding the below code and try whether the animation works..
-(void) animateSubViews
{
int buffer = 10;
CGRect frame = CGRectMake((self.pageControl.currentPage * self.scrollView.frame.size.width)-buffer, 0, self.scrollView.frame.size.width + buffer, self.scrollView.frame.size.height);
[UIView animateWithDuration:0.4
animations:^{
for (UIView *view in self.scrollView.subviews)
{
if (CGRectContainsRect(frame, view.frame))
{
[view setAlpha:1.0];
}
else
{
[view setAlpha:0.0];
}
}
}];
}
Try calling this method from ScrollView did scroll and change page.
- (IBAction)changePage:(id)sender {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * self.pageControl.currentPage;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
[self.scrollView scrollRectToVisible:frame animated:YES];
//Call to animate
[self animateSubViews];
}
- (void)scrollViewDidScroll:(UIScrollView *)sender
{
// Update the page when more than 50% of the previous/next page is visible
CGFloat pageWidth = self.scrollView.frame.size.width;
int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
self.pageControl.currentPage = page;
//Call to animate
[self animateSubViews];
}

Change image of a scrollview or replace the array of images

I have a problem with changing images in the scrollview, the scrollview problem is that depending on the action that makes me have to change the image that contains other, as I do not change the picture or the array of images, I need help, thanks
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *imgNames = [[NSMutableArray alloc] initWithObjects:#"cooper.png", #"cabrio.png",#"country.png", nil];
NSMutableArray *imgArray = [[NSMutableArray alloc] init];
UIImageView *tempImageView;
for(NSString *name in imgNames) {
tempImageView = [[UIImageView alloc] init];
tempImageView.contentMode = UIViewContentModeScaleAspectFit;
tempImageView.image = [UIImage imageNamed:name];
[imgArray addObject:tempImageView];
}
CGSize pageSize = scrollView.frame.size;
NSUInteger page = 0;
for(UIView *view in imgArray) {
[scrollView addSubview:view];
view.frame = CGRectMake(pageSize.width * page++ + 10, 0, pageSize.width - 20, pageSize.height);
}
scrollView.contentSize = CGSizeMake(pageSize.width * [imgArray count], pageSize.height);
}
- (IBAction)btnAction:(id)sender {
NSMutableArray *imgNames = [[NSMutableArray alloc] initWithObjects:#"hello.png", #"bye.png",#"trues.png", nil];
NSMutableArray *imgArray = [[NSMutableArray alloc] init];
UIImageView *tempImageView;
for(NSString *name in imgNames) {
tempImageView = [[UIImageView alloc] init];
tempImageView.contentMode = UIViewContentModeScaleAspectFit;
tempImageView.image = [UIImage imageNamed:name];
[imgArray addObject:tempImageView];
}
CGSize pageSize = scrollView.frame.size;
NSUInteger page = 0;
for(UIView *view in imgArray) {
[scrollView addSubview:view];
view.frame = CGRectMake(pageSize.width * page++ + 10, 0, pageSize.width - 20, pageSize.height);
}
scrollView.contentSize = CGSizeMake(pageSize.width * [imgArray count], pageSize.height);
}
}
You can directly set the image alone if UIImageView is already allocated in viewDidLoad like,
for(UIImageView *view in imgArray) {
view.image = [UIImage imageNamed:[imgNames objectAtIndex:[imgArray indexOfObject:view]]]
}

CATiledLayer and not rendered slices

The problem:
I've to render a big image 7148x15000px (a custom map), so i've looking around for something usefull and i've found BitmapSlice, but the problem is that the very first time i run the app (on device and simulator) several slices aren't loaded correctly and i see the image with large black holes.
Code:
BitmapSliceViewController.h
#import <UIKit/UIKit.h>
#interface BitmapSliceViewController : UIViewController<UIScrollViewDelegate>
#property (nonatomic, retain) UIImageView *_zoomView;
#property (nonatomic, retain) IBOutlet UIScrollView *scrollView;
- (void)saveTilesOfSize:(CGSize)size forImage:(UIImage*)image toDirectory
(NSString*)directoryPath usingPrefix:(NSString*)prefix;
#end
BitmapSliceViewController.m
#import "BitmapSliceViewController.h"
#import "TileView.h"
#implementation BitmapSliceViewController
#synthesize scrollView;
- (void)dealloc
{
[super dealloc];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *directoryPath = [paths objectAtIndex:0];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
UIImage *big = [UIImage imageNamed:#"map.jpg"];
[self saveTilesOfSize:(CGSize){256, 256} forImage:big toDirectory:directoryPath usingPrefix:#"map_"];
dispatch_async(dispatch_get_main_queue(), ^{
[scrollView setNeedsDisplay];
});
});
TileView *tv = [[TileView alloc] initWithFrame:(CGRect){{0,0}, (CGSize){7148,15000}}];
[tv setTileTag:#"map_"];
[tv setTileDirectory:directoryPath];
[scrollView addSubview:tv];
[scrollView setContentSize:(CGSize){7148,15000}];
[scrollView setDelegate:self];
}
- (void)saveTilesOfSize:(CGSize)size
forImage:(UIImage*)image
toDirectory:(NSString*)directoryPath
usingPrefix:(NSString*)prefix
{
CGFloat cols = [image size].width / size.width;
CGFloat rows = [image size].height / size.height;
int fullColumns = floorf(cols);
int fullRows = floorf(rows);
CGFloat remainderWidth = [image size].width - (fullColumns * size.width);
CGFloat remainderHeight = [image size].height - (fullRows * size.height);
if (cols > fullColumns) fullColumns++;
if (rows > fullRows) fullRows++;
CGImageRef fullImage = [image CGImage];
for (int y = 0; y < fullRows; ++y) {
for (int x = 0; x < fullColumns; ++x) {
CGSize tileSize = size;
if (x + 1 == fullColumns && remainderWidth > 0) {
// Last column
tileSize.width = remainderWidth;
}
if (y + 1 == fullRows && remainderHeight > 0) {
// Last row
tileSize.height = remainderHeight;
}
CGImageRef tileImage = CGImageCreateWithImageInRect(fullImage,
(CGRect){{x*size.width, y*size.height},
tileSize});
NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:tileImage], 1);
CGImageRelease(tileImage);
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png",
directoryPath, prefix, x, y];
[imageData writeToFile:path atomically:NO];
}
}
}
#end
TileView.h
#interface TileView : UIView
#property (nonatomic, copy) NSString *tileTag;
#property (nonatomic, copy) NSString *tileDirectory;
- (UIImage*)tileAtCol:(int)col row:(int)row;
#end
TileView.m
#import "TileView.h"
#implementation TileView
#synthesize tileTag;
#synthesize tileDirectory;
+ layerClass
{
return [CATiledLayer class];
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (!self) return nil;
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)drawRect:(CGRect)rect {
//CGContextRef context = UIGraphicsGetCurrentContext();
CGSize tileSize = (CGSize){256, 256};
int firstCol = floorf(CGRectGetMinX(rect) / tileSize.width);
int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize.width);
int firstRow = floorf(CGRectGetMinY(rect) / tileSize.height);
int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize.height);
for (int row = firstRow; row <= lastRow; row++) {
for (int col = firstCol; col <= lastCol; col++) {
UIImage *tile = [self tileAtCol:col row:row];
if (tile)
{
CGRect tileRect = CGRectMake(tileSize.width * col, tileSize.height * row, tileSize.width, tileSize.height);
tileRect = CGRectIntersection(self.bounds, tileRect);
[tile drawInRect:tileRect];
// [[UIColor whiteColor] set];
// CGContextSetLineWidth(context, 6.0);
// CGContextStrokeRect(context, tileRect);
}
}
}
}
- (UIImage*)tileAtCol:(int)col row:(int)row
{
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png", tileDirectory, tileTag, col, row];
return [UIImage imageWithContentsOfFile:path];
}
#end
This is the main code of the app, you can download the entire example from the site linked on the top of the post.
As i said the main problem is the rendering of some slices that fail in the first run of the app, other runs seem works correctly.
modifing a bit - (UIImage*)tileAtCol:(int)col row:(int)row
- (UIImage*)tileAtCol:(int)col row:(int)row
{
NSString *path = [NSString stringWithFormat:#"%#/%#%d_%d.png", tileDirectory, tileTag, col, row];
UIImage *img = [UIImage imageWithContentsOfFile:path];
if (img) {
NSLog(#"good");
}
else {
NSLog(#"bad");
}
return img;
}
The problem seems to be here...
Any ideas to fix it?
Thanks in advance

Resources