Image not centered vertically in scrollview - objective-c

What am I missing? The inner scrollview and the image view fill the entire screen. But somehow my image is not centered. The top left corner of the image starts in the center of the view, but I would like to have the image nicely centered. Also during zooming.
-(void)prepareScrollView
{
for(int i =0;i<[self.layoverPhotoAssets count];i++){
PHAsset *asset = self.layoverPhotoAssets[i];
FMImageZoomViewController *zoomController = [[FMImageZoomViewController alloc] init];
// UIImageView *imageView = [[UIImageView alloc] init];
int x = self.scrollView.frame.size.width * i;
zoomController.view.frame = CGRectMake(x, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
//zoomController.view.frame = CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height);
[self.scrollView addSubview:zoomController.view];
zoomController.zoomScroller.delegate = self;
zoomController.imageView.tag = 1;
[self.zoomControllers addObject:zoomController];
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.resizeMode = PHImageRequestOptionsResizeModeFast;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; //I only want the highest possible quality
options.synchronous = NO;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:zoomController.zoomScroller.frame.size contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
if(result){
zoomController.imageView.image = result;
zoomController.imageView.backgroundColor = [UIColor redColor];
}
});
}];
//self.scrollView.contentSize= ;
}
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width * [self.layoverPhotoAssets count], 0)];
[self scrollToAsset:self.selectedAsset];
}

Consider:
zoomController.view.frame = CGRectMake(x, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
[self.scrollView addSubview:zoomController.view];
That cannot be right. If zoomController.view is to be a subview of self.scrollView, its frame within self.scrollView is in terms of the bounds of self.scrollView, not the frame of self.scrollView.

Solved it like this:
-(void)prepareScrollView
{
for(int i =0;i<[self.layoverPhotoAssets count];i++){
PHAsset *asset = self.layoverPhotoAssets[i];
FMImageZoomViewController *zoomController = [[FMImageZoomViewController alloc] init];
// UIImageView *imageView = [[UIImageView alloc] init];
int x = self.scrollView.frame.size.width * i;
zoomController.view.frame = CGRectMake(x, 0, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
//zoomController.view.frame = CGRectMake(0,0,self.view.bounds.size.width,self.view.bounds.size.height);
[self.scrollView addSubview:zoomController.view];
zoomController.zoomScroller.delegate = self;
[self.zoomControllers addObject:zoomController];
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.resizeMode = PHImageRequestOptionsResizeModeExact;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; //I only want the highest possible quality
options.synchronous = NO;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:zoomController.zoomScroller.bounds.size contentMode:PHImageContentModeAspectFit options:options resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
if(result){
zoomController.imageView = [[UIImageView alloc] initWithImage:result];
zoomController.imageView.frame = zoomController.zoomScroller.bounds;
[zoomController.imageView setContentMode:UIViewContentModeScaleAspectFit];
zoomController.imageView.clipsToBounds = YES;
[zoomController.imageView setCenter: self.scrollView.center];
zoomController.imageView.tag = 1;
[zoomController.zoomScroller addSubview:zoomController.imageView];
// zoomController.imageView.contentMode = UIViewContentModeCenter;
// if (zoomController.imageView.bounds.size.width > result.size.width && zoomController.imageView.bounds.size.height > result.size.height) {
// zoomController.imageView.contentMode = UIViewContentModeScaleAspectFit;
// }
}
});
}];
//self.scrollView.contentSize= ;
}
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width * [self.layoverPhotoAssets count], 0)];
[self scrollToAsset:self.selectedAsset];
}

Related

CAGradientLayer in UILabel in UIStackView

This is a custom UIView subclass for a tableHeaderView.
I'm currently trying to put a gradient to an UILabel that's in a vertical UIStackView. It works really well without gradient even in RTL languages (gets moved to the right), but as soon as I add the gradient, the label that's the maskView of the gradientView gets completely out of its place. Here the code for better comprehension:
- (instancetype)initWithTitle:(NSString *)title subtitle:(NSString *)subtitle colors:(NSArray<UIColor *> *)colors {
if (self = [super initWithFrame:CGRectMake(0, 0, self.superview.frame.size.width, 200)]) {
// Labels
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.text = title;
titleLabel.font = [UIFont boldSystemFontOfSize:42.f];
titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[titleLabel sizeToFit];
UILabel *subtitleLabel = [[UILabel alloc] init];
subtitleLabel.text = subtitle;
subtitleLabel.font = [UIFont systemFontOfSize:24.f];
subtitleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[subtitleLabel sizeToFit];
// Create gradient
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = titleLabel.bounds;
NSMutableArray *cgcolors = [NSMutableArray new];
for (int i = 0; i < colors.count; i++) {
cgcolors[i] = (id)colors[i].CGColor;
}
gradient.colors = cgcolors;
gradient.locations = #[#0, #1];
UIView *gradientView = [[UIView alloc] initWithFrame:titleLabel.bounds];
[gradientView.layer addSublayer:gradient];
[gradientView addSubview:titleLabel];
gradientView.maskView = titleLabel;
// Stack
UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews:#[gradientView, subtitleLabel]];
stackView.alignment = UIStackViewAlignmentLeading;
stackView.axis = UILayoutConstraintAxisVertical;
stackView.distribution = UIStackViewDistributionEqualCentering;
stackView.spacing = 0;
stackView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:stackView];
[NSLayoutConstraint activateConstraints:#[
[stackView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:25],
[stackView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
[stackView.heightAnchor constraintEqualToConstant:titleLabel.frame.size.height + subtitleLabel.frame.size.height]
]];
}
return self;
}
With LTR languages, it looks good, but with RTL languages, the frame of the gradientView that contains the titleLabel becomes {[width of subtitleLabel], 0, 0, 0} for no reason. The cause is the gradient view, because without it it works fine, but I can't find why.
I tried titleLabel.layer.mask, placing the gradient block at the end, but nothing worked.
EDIT :
Working code:
- (instancetype)initWithTitle:(NSString *)title subtitle:(NSString *)subtitle colors:(NSArray<__kindof UIColor *> *)colors {
if (self = [super initWithFrame:CGRectMake(0, 0, self.superview.frame.size.width, 200)]) {
// Labels
UILabel *titleLabel = [[UILabel alloc] init];
titleLabel.text = title;
titleLabel.font = [UIFont boldSystemFontOfSize:42.f];
titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[titleLabel sizeToFit];
UILabel *subtitleLabel = [[UILabel alloc] init];
subtitleLabel.text = subtitle;
subtitleLabel.font = [UIFont systemFontOfSize:24.f];
subtitleLabel.lineBreakMode = NSLineBreakByWordWrapping;
[subtitleLabel sizeToFit];
// Create gradient
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = titleLabel.bounds;
NSMutableArray *cgcolors = [NSMutableArray new];
for (int i = 0; i < colors.count; i++) {
cgcolors[i] = (id)colors[i].CGColor;
}
gradient.colors = cgcolors;
gradient.locations = #[#0, #1];
UIView *gradientView = [[UIView alloc] init];
[gradientView.layer addSublayer:gradient];
gradientView.maskView = titleLabel;
// Stack
UIStackView *stackView = [[UIStackView alloc] initWithArrangedSubviews:#[gradientView, subtitleLabel]];
stackView.alignment = UIStackViewAlignmentLeading;
stackView.axis = UILayoutConstraintAxisVertical;
stackView.distribution = UIStackViewDistributionEqualCentering;
stackView.spacing = 0;
stackView.translatesAutoresizingMaskIntoConstraints = NO;
[self addSubview:stackView];
[NSLayoutConstraint activateConstraints:#[
[stackView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:25],
[stackView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
[stackView.heightAnchor constraintEqualToConstant:titleLabel.frame.size.height + subtitleLabel.frame.size.height],
[gradientView.widthAnchor constraintEqualToConstant:titleLabel.frame.size.width],
[gradientView.heightAnchor constraintEqualToConstant:titleLabel.frame.size.height]
]];
}
return self;
}
The problem is that your gradientView has no intrinsic content size.
Try changing your constraints to this:
[NSLayoutConstraint activateConstraints:#[
[stackView.leadingAnchor constraintEqualToAnchor:self.leadingAnchor constant:25],
[stackView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor],
// shouldn't need to set a height anchor on the stackView
//[stackView.heightAnchor constraintEqualToConstant:titleLabel.frame.size.height + subtitleLabel.frame.size.height],
[gradientView.widthAnchor constraintEqualToConstant:titleLabel.frame.size.width],
[gradientView.heightAnchor constraintEqualToConstant:titleLabel.frame.size.height],
]];

UIScrollView with pageable image gallery - Any memory problems? And what about zooming?

I want to have a similar functionality as in the Photos app on the iPhone in my Scrollview. So I've added all images to my scrollview like this and it works nicely.
-(void)prepareScrollView
{
for(int i =0;i<[self.layoverPhotoAssets count];i++){
PHAsset *asset = self.layoverPhotoAssets[i];
UIImageView *imageView = [[UIImageView alloc] init];
int x = self.scrollView.frame.size.width * i;
imageView.frame = CGRectMake(x, 0, self.scrollView.frame.size.width, self.scrollView.frame.size.height);
imageView.contentMode = UIViewContentModeScaleAspectFit;
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
options.resizeMode = PHImageRequestOptionsResizeModeFast;
options.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat; //I only want the highest possible quality
options.synchronous = NO;
options.networkAccessAllowed = YES;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:self.scrollView.frame.size contentMode:PHImageContentModeAspectFill options:options resultHandler:^(UIImage *result, NSDictionary *info) {
dispatch_async(dispatch_get_main_queue(), ^{
if(result){
imageView.image = result;
}
});
}];
[self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width * (i + 1), self.scrollView.frame.size.height)];
//self.scrollView.contentSize= ;
[self.scrollView addSubview:imageView];
}
}
However I have 2 questions:
1. Like this, all images will be loaded at once. Memory wise this is quite bad. How can I improve that without worsening the user experience?
2. How can I make the image itself zoomable?

CGRect intersection from child to self

Question
How to achieve an intersection of two sprites, when one is a child of self and the other is a child of a sprite?
As their positions are completely different relevant to the comparisons between each other?
Example; this is ran before each frame to determine whether they intersect
-(void)checkInFOVWithPlayer:(Player *)player andEnemy:(Player *)enemy {
SKNode *node = [player childNodeWithName:player.playersFOVName];
if (CGRectIntersectsRect(node.frame, enemy.frame)) {
// [self playerAimAtEnemy:enemy withPlayer:player];
NSLog(#"inframe");
} else {
NSLog(#" ");
}
}
However, node is a child of player and enemy is a child of self. So how can you check if they intersect?
Here's where they're initialised
float radianAngle = ((fovAngle) / 180.0 * M_PI);
float fovOpposite = atanf(radianAngle) * fovDistance;
SKShapeNode *fov = [SKShapeNode node];
UIBezierPath *fovPath = [[UIBezierPath alloc] init];
[fovPath moveToPoint:CGPointMake(0, 0)];
[fovPath addLineToPoint:CGPointMake(fovOpposite *-1, fovDistance)];
[fovPath addLineToPoint:CGPointMake(fovOpposite, fovDistance)];
[fovPath addLineToPoint:CGPointMake(0, 0)];
fov.path = fovPath.CGPath;
fov.lineWidth = 1.0;
fov.strokeColor = [UIColor clearColor];
fov.antialiased = NO;
fov.fillColor = [UIColor greenColor];
fov.alpha = 0.2;
fov.name = #"playerFOV";
[_playerImage addChild:fov];
and enemy
NSString *bundle = [[NSBundle mainBundle] pathForResource:#"enemyImage" ofType:#"png"];
UIImage *image = [[UIImage alloc] initWithContentsOfFile:bundle];
SKTexture *texture = [SKTexture textureWithImage:image];
_enemy = [Player spriteNodeWithTexture:texture];
_enemy.position = CGPointMake(100, 100);
_enemy.size = CGSizeMake(20, 20);
_enemy.playerAimAngle = [self returnRandomNumberBetween:0 to:360];
_enemy.anchorPoint = CGPointMake(0.5, 0.5);
_enemy.playerHealth = 100;
_enemy.playerIsDead = false;
[self addChild:_enemy];
-(void)checkInFOVWithPlayer:(Player *)player andEnemy:(Player *)enemy {
SKNode *fovNode = [player childNodeWithName:player.playersFOVName];
SKNode *node = [self childNodeWithName:#"enemy"];
CGPoint newPosition = [self convertPoint:node.position toNode:fovNode.parent];
if (CGRectContainsPoint(fovNode.frame, newPosition)) {
[self playerAimAtEnemy:enemy withPlayer:player];
}
}
This has ended up being my solution to the problem, Now however, I must find a way to change the frame of the node so that it is not rectangular.

How do I dismiss a UIView after scanning a barcode?

I have an iPad app that I want to add a barcode reader to... this is the code for the initialization of the barcoder code:
-(void) scanInitializationCode {
_highlightView = [[UIView alloc] init];
_highlightView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleBottomMargin;
_highlightView.layer.borderColor = [UIColor greenColor].CGColor;
_highlightView.layer.borderWidth = 3;
[self.view addSubview:_highlightView];
// define the label to display the results of the scan
_label = [[UILabel alloc] init];
_label.frame = CGRectMake(0, self.view.bounds.size.height - 40, self.view.bounds.size.width, 40);
_label.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
_label.backgroundColor = [UIColor colorWithWhite:0.15 alpha:0.65];
_label.textColor = [UIColor whiteColor];
_label.textAlignment = NSTextAlignmentCenter;
_label.text = #"(none)";
[self.view addSubview:_label];
// session initialization
_session = [[AVCaptureSession alloc] init];
_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
// define the input device
_input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:&error];
if (_input) {
[_session addInput:_input];
} else {
NSLog(#"Error: %#", error);
}
// and output device
_output = [[AVCaptureMetadataOutput alloc] init];
[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
[_session addOutput:_output];
_output.metadataObjectTypes = [_output availableMetadataObjectTypes];
// and preview layer
_prevLayer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
_prevLayer.frame = self.view.bounds;
_prevLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
[self.view.layer addSublayer:_prevLayer];
}
This is the AVCaptureMetadataOutputObjectsDelegate code:
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
CGRect highlightViewRect = CGRectZero;
AVMetadataMachineReadableCodeObject *barCodeObject;
NSString *detectionString = nil;
NSArray *barCodeTypes = #[AVMetadataObjectTypeEAN13Code];
for (AVMetadataObject *metadata in metadataObjects) {
for (NSString *type in barCodeTypes) {
if ([metadata.type isEqualToString:type])
{
barCodeObject = (AVMetadataMachineReadableCodeObject *)[_prevLayer transformedMetadataObjectForMetadataObject:(AVMetadataMachineReadableCodeObject *)metadata];
highlightViewRect = barCodeObject.bounds;
detectionString = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
break;
}
}
if (detectionString != nil) {
_label.text = detectionString;
oISBNField.text = detectionString; // move detectionString to ISBN textbox
[_session stopRunning];
[_highlightView removeFromSuperview];
break;
}
else
_label.text = #"(none)";
}
This is the code that starts the scanning process by having the user tap a UIButton:
- (IBAction)aReadBarcode:(UIButton *)sender {
[self scanInitializationCode];
[_session startRunning];
// display the activity
[self.view bringSubviewToFront:_highlightView];
[self.view bringSubviewToFront:_label];
oISBNField.text = scanResults;
}
The problem is that once the scan has found the barcode, it stays visible; what I want to do is have it return to the UIView that has the button that caused it to start scanning (in other words, I want the _highlightView to disappear). I have tried all kinds of "dismissal" methods, even putting it at the back of the z-order, but none of them work. How can I make the highlightView disappear from the screen?
The answer:
[_prevLayer removeFromSuperlayer]; after [_session stopRunning]

Activity Indicator while loading images inside UIScrollView

I have UIScrollView that contains images from the server.
I should put Activity Indicator while the image is currently loading.
UIScrollView contains dynamic number of images from the server.
May I know how can I add activity indicators on each page while the image is loading and remove once image is loaded.
Here's my code to retrieve images:
NSDictionary *items = [NSDictionary dictionaryWithObject:dictInfo forKey:#"images"];
imageList = [items objectForKey:#"images"];
NSArray *img = [imageList objectForKey:#"list"];
NSInteger imgCount = [img count];
buttonArray = [[NSMutableArray alloc] init];
for (int i=0; i<imgCount; i++) {
NSDictionary *imgDict = [img objectAtIndex:i];
// REQUEST FOR IMAGES
NSString *imgPath = [imgDict objectForKey:#"image_slot"];
NSString *imgURL = imgPath;
__block ASIHTTPRequest *requestImage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:imgURL]];
[requestImage setCompletionBlock:^{
imgView = [UIImage imageWithData:[requestImage responseData]];
if (imgURL.length) {
[pendingRequests removeObjectForKey:imgURL];
}
scrollView.userInteractionEnabled = YES;
scrollView.exclusiveTouch = YES;
scrollView.canCancelContentTouches = YES;
scrollView.delaysContentTouches = YES;
scrollView.bounces = NO;
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;
SWTUIButton *imgBtn = [[SWTUIButton alloc] initWithFrame:frame];
imgBtn.url = [requestImage.userInfo objectForKey:#"rURL"];
[imgBtn setImage:imgView forState:UIControlStateNormal];
imgBtn.backgroundColor = [UIColor clearColor];
[imgBtn addTarget:self action:#selector(buttonpushed:) forControlEvents:UIControlEventTouchUpInside];
[scrollView addSubview:imgBtn];
[buttonArray addObject:imgBtn];
[imgBtn release];
self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width * img.count, self.scrollView.frame.size.height);
}];
I highly suggest you use NINetworkImageView from https://github.com/jverkoey/nimbus project.
It's very light and useful.
It has a delegate method to let you know when an image is loaded.
What you basically need to do is:
1. create an NINetworkImageView for each page, just like you do with UIImageView, and call set
NINetworkImageView* networkImageView = [[[NINetworkImageView alloc] initWithImage:initialImage]
autorelease];
networkImageView.delegate = self;
networkImageView.contentMode = UIViewContentModeCenter;
[networkImageView setPathToNetworkImage:
#"http://farm3.static.flickr.com/2484/3929945380_deef6f4962_z.jpg"
forDisplaySize: CGSizeMake(kImageDimensions, kImageDimensions)];
https://github.com/jverkoey/nimbus/tree/master/examples/photos/NetworkPhotoAlbums
the add the indicator to the networkImageView as a subview.
implement the delegate as follows:
-(void)networkImageView:(NINetworkImageView *)imageView didLoadImage:(UIImage *)image {
[imageView removeAllSubviews];
}
the end result would be a much smaller code for doing the same thing.