Converting between Cocoa and Carbon coordinates? - objective-c

I am looking for a robust (I mean working in all multi-munitor configuration) algo to convert a cocoa point/rect to carbon equivalent and the reverse operation.
I've googled but was unable to find something which work properly.
Thanks in advance for your help.
Regards,

After several iterations I got to the following category on NSScreen:
+ (NSScreen*) screenWithPoint: (NSPoint) p
{
for (NSScreen *candidate in [NSScreen screens])
if (NSPointInRect(p, [candidate frame]))
return candidate;
return nil;
}
+ (NSScreen*) screenWithMenuBar
{
return [self screenWithPoint:NSZeroPoint];
}
+ (float) menuScreenHeight
{
return NSMaxY([[self screenWithMenuBar] frame]);
}
+ (CGPoint) carbonPointFrom: (NSPoint) cocoaPoint
{
return CGPointMake(cocoaPoint.x, [self menuScreenHeight] - cocoaPoint.y);
}
+ (NSPoint) cocoaPointFrom: (CGPoint) carbonPoint
{
return NSMakePoint(carbonPoint.x, [self menuScreenHeight] - carbonPoint.y);
}
This works fine even with multiple displays.

The posted code from Apple's code from UIElementInspector turn out to be buggy, in that it doesn't account for the origin of a non-main screen. The fixed (and refactored) code looks like this:
+ (CGPoint)carbonScreenPointFromCocoaScreenPoint:(NSPoint)cocoaPoint {
NSScreen* foundScreen = nil;
NSRect screenFrame;
for (NSScreen* screen in [NSScreen screens]) {
screenFrame = [screen frame];
if (NSPointInRect(cocoaPoint, screenFrame)) {
foundScreen = screen;
break;
}
}
if (! foundScreen) return CGPointMake(0.0, 0.0);
return CGPointMake(cocoaPoint.x,
screenFrame.origin.y + screenFrame.size.height - cocoaPoint.y);
}

Or take Apple's code from UIElementInspector sample project:
+ (CGPoint)carbonScreenPointFromCocoaScreenPoint:(NSPoint)cocoaPoint
{
NSScreen *foundScreen = nil;
CGPoint thePoint;
for (NSScreen *screen in [NSScreen screens])
{
if (NSPointInRect(cocoaPoint, [screen frame]))
{
foundScreen = screen;
}
}
if (foundScreen)
{
CGFloat screenHeight = [foundScreen frame].size.height;
thePoint = CGPointMake(cocoaPoint.x, screenHeight - cocoaPoint.y - 1);
}
else
{
thePoint = CGPointMake(0.0, 0.0);
}
return thePoint;
}

Related

How to receive mouseDown messages in a NSTableViewCell?

I am trying to make a table view cell that shows ratings for songs in a playlist. I have successfully created the cell so that it shows the current number of stars, and also an indication of how a new setting will be when you hover your mouse cursor over a cell to give a new rating.
The problem is that while mouseEnter, mouseExit and mouseMove works like a charm, I get no messages for mouseDown, which is required to actually change the value of the cell.
I have searched all over the Internet, but I can't find any solution to how to solve this problem anywhere. I have spent so many hours trying to sort this. I hope anyone have any answer or hint what I can do. Thank you.
The full code for the current implementation is as follows:
#import "FavouriteCellView.h"
#implementation FavouriteCellView {
NSTrackingArea *_trackingArea;
int _starsRated; //The current rating value
BOOL _hovering; //YES if the mouse is currently hovering over this cell
int _starsHovering; //The number of stars hovering, if the mouse is hovering over this cell
}
- (void)awakeFromNib {
[super awakeFromNib];
_starsRated = 1;
_hovering = NO;
_starsHovering = 0;
[self createTrackingArea];
}
- (void)createTrackingArea
{
_trackingArea = [[NSTrackingArea alloc] initWithRect:self.bounds options:NSTrackingMouseEnteredAndExited |NSTrackingActiveInActiveApp | NSTrackingMouseMoved owner:self userInfo:nil];
[self addTrackingArea:_trackingArea];
}
- (void)updateTrackingAreas{
[self removeTrackingArea:_trackingArea];
_trackingArea = nil;
[self createTrackingArea];
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
// CGFloat middleX = [self bounds].size.width / 2.0f;
CGFloat middleY = [self bounds].size.height / 2.0f;
CGFloat starDivs = [self bounds].size.width / 5.0f;;
NSColor *starSelectedColor = [NSColor colorWithDeviceRed:0.8f green:0.0f blue:0.4f alpha:1.0f];
NSColor *starUnselectedColor = [NSColor colorWithDeviceRed:0.5f green:0.5f blue:0.5f alpha:1.0f];
NSColor *starHoverColor = [NSColor colorWithDeviceRed:1.0f green:0.843f blue:0.0f alpha:1.0f];
NSColor *starHoverColorSelected = [NSColor colorWithDeviceRed:0.9f green:0.843f blue:0.6f alpha:1.0f];
for (int i = 0; i < 5; i++) {
NSColor *useColor = [NSColor redColor];
if (_hovering && (i <= _starsHovering)) {
if (i <= _starsRated) {
useColor = starHoverColorSelected;
} else {
useColor = starHoverColor;
}
} else if (i <= _starsRated) {
useColor = starSelectedColor;
} else {
useColor = starUnselectedColor;
}
[self star:NSMakePoint((starDivs / 2.0f) + starDivs * i, middleY) color:useColor];
}
}
-(void)star:(NSPoint)center color:(NSColor *)color {
[color set];
CGFloat t = (2.0f * M_PI) / 10.0f;
NSBezierPath *path = [[NSBezierPath alloc] init];
CGFloat radii1 = 12.0f;
CGFloat radii2 = 4.0f;
CGFloat rot = M_PI / 2.0f;
BOOL first = YES;
for (int i = 0; i < 10; i++) {
CGFloat pointX = cos(t * i + rot) * radii1 + center.x;
CGFloat pointY = sin(t * i + rot) * radii1 + center.y;
CGFloat tempRadii = radii1;
radii1 = radii2;
radii2 = tempRadii;
if (first) {
first = NO;
[path moveToPoint:NSMakePoint(pointX, pointY)];
}
else {
[path lineToPoint:NSMakePoint(pointX, pointY)];
}
}
[path closePath];
[path fill];
/*
[[NSColor blackColor] set];
[path setLineWidth:0.25f];
[path stroke];
*/
}
-(NSView *)hitTest:(NSPoint)aPoint {
//THIS GETS CALLED
return self;
}
-(BOOL)validateProposedFirstResponder:(NSResponder *)responder forEvent:(NSEvent *)event {
printf("$"); //DOES NOT GET CALLED
return YES;
}
-(BOOL)acceptsFirstResponder {
printf("!"); //DOES NOT GET CALLED
return YES;
}
-(BOOL)acceptsFirstMouse:(NSEvent *)theEvent {
printf("8"); //DOES NOT GET CALLED
return YES;
}
-(void)mouseDown:(NSEvent *)theEvent {
printf("o"); //DOES NOT GET CALLED
_starsRated = _starsHovering;
}
-(void)mouseUp:(NSEvent *)theEvent {
printf("O"); //DOES NOT GET CALLED
}
-(void)mouseEntered:(NSEvent *)theEvent {
//DOES GET CALLED
_hovering = YES;
[self setNeedsDisplay:YES];
}
-(void)mouseExited:(NSEvent *)theEvent {
//DOES GET CALLED
_hovering = NO;
[self setNeedsDisplay:YES];
}
-(void)mouseMoved:(NSEvent *)theEvent {
//DOES GET CALLED
NSPoint mouseLocation = [[self window] mouseLocationOutsideOfEventStream];
mouseLocation = [self convertPoint: mouseLocation
fromView: nil];
int newStarsHoveringValue = mouseLocation.x / ([self bounds].size.width / 5.0f);
if (newStarsHoveringValue != _starsHovering) {
_starsHovering = newStarsHoveringValue;
[self setNeedsDisplay:YES];
}
}
#end
It was a bit fiddly, but I managed to create a solution that works. I subclassed NSTableView, then overrode mouseDown with the following code:
-(void)mouseDown:(NSEvent *)theEvent {
NSPoint globalLocation = [theEvent locationInWindow];
NSPoint localLocation = [self convertPoint:globalLocation fromView:nil];
NSInteger clickedRow = [self rowAtPoint:localLocation];
if (clickedRow != -1) {
NSInteger clickedColumn = [self columnAtPoint:localLocation];
if (clickedColumn != -1) {
if (clickedColumn == 3) {
FavouriteCellView *fv = [self viewAtColumn:clickedColumn row:clickedRow makeIfNecessary:NO];
if (fv != nil) {
[fv mouseDown:theEvent];
}
return;
}
}
}
[super mouseDown:theEvent];
}
Now it works exactly like I wanted.

Recognize a path of user gesture

I'm working on an app with 9 views on screen, and I want the users to connect the views in a way they want, and record their sequence as password.
But I don't know which gesture recognizer I should use.
Should I use CMUnistrokeGestureRecognizer or combination of several swipe gesture or anything else?
Thanks.
You could use a UIPanGestureRecognizer, something like:
CGFloat const kMargin = 10;
- (void)viewDidLoad
{
[super viewDidLoad];
// create a container view that all of our subviews for which we want to detect touches are:
CGFloat containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - kMargin * 2.0;
UIView *container = [[UIView alloc] initWithFrame:CGRectMake(kMargin, kMargin, containerWidth, containerWidth)];
container.backgroundColor = [UIColor darkGrayColor];
[self.view addSubview:container];
// now create all of the subviews, specifying a tag for each; and
CGFloat cellWidth = (containerWidth - (4.0 * kMargin)) / 3.0;
for (NSInteger column = 0; column < 3; column++)
{
for (NSInteger row = 0; row < 3; row++)
{
UIView *cell = [[UIView alloc] initWithFrame:CGRectMake(kMargin + column * (cellWidth + kMargin),
kMargin + row * (cellWidth + kMargin),
cellWidth, cellWidth)];
cell.tag = row * 3 + column;
cell.backgroundColor = [UIColor lightGrayColor];
[container addSubview:cell];
}
}
// finally, create the gesture recognizer
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self
action:#selector(handlePan:)];
[container addGestureRecognizer:pan];
}
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
// an example of the sort of graphical flourish to give the
// some visual cue that their going over the subview in question
// was recognized
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
NSLog(#"We went over:");
for (UIView *subview in gesturedSubviews)
{
NSLog(#" %d", subview.tag);
}
// you might as well clean up your static variable when you're done
gesturedSubviews = nil;
}
}
Obviously, you would create your subviews any way you want, and keep track of them any way you want, but the idea is to have subviews with unique tag numbers, and the gesture recognizer would just see which order you go over them in a single gesture.
Even if I didn't capture precisely what you want, it at least shows you how you can use a pan gesture recognizer to track the movement of your finger from one subview to another.
Update:
If you wanted to draw a path on the screen as the user is signing in, you could create a CAShapeLayer with a UIBezierPath. I'll demonstrate that below, but as a caveat, I feel compelled to point out that this might not be a great security feature: Usually with password entry, you'll show the user enough so that they can confirm that they're doing what they want, but not enough so that someone can glance look over their shoulder and see what the whole password was. When entering a text password, usually iOS momentarily shows you the last key you hit, but quickly turns that into an asterisk so that, at no point, can you see the whole password. Hence my initial suggestion.
But if you really have your heart set on showing the user the path as they draw it, you could use something like the following. First, this requires Quartz 2D. Thus add the QuartzCore.framework to your project (see Linking to a Library or Framework). Second, import the QuartCore headers:
#import <QuartzCore/QuartzCore.h>
Third, replace the pan handler with something like:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
static UIBezierPath *path = nil;
static CAShapeLayer *shapeLayer = nil;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (!path)
{
// if the path hasn't be started, initialize it and the shape layer
path = [UIBezierPath bezierPath];
[path moveToPoint:location];
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 2.0;
[gesture.view.layer addSublayer:shapeLayer];
}
else
{
// otherwise add this point to the layer's path
[path addLineToPoint:location];
shapeLayer.path = path.CGPath;
}
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
// assuming the tags are numbers between 0 and 9 (inclusive), we can build the password here
NSMutableString *password = [NSMutableString string];
for (UIView *subview in gesturedSubviews)
[password appendFormat:#"%c", subview.tag + 48];
NSLog(#"Password = %#", password);
// clean up our array of gesturedSubviews
gesturedSubviews = nil;
// clean up the drawing of the path on the screen the user drew
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
path = nil;
}
}
That yields a path that the user draws as the gesture proceeds:
Rather than showing the path the user draws with each and every movement of the user's finger, maybe you just draw the lines between the center of the subviews, such as:
- (void)handlePan:(UIPanGestureRecognizer *)gesture
{
static NSMutableArray *gesturedSubviews;
static UIBezierPath *path = nil;
static CAShapeLayer *shapeLayer = nil;
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == UIGestureRecognizerStateBegan)
{
gesturedSubviews = [NSMutableArray array];
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
CGPoint location = [gesture locationInView:gesture.view];
for (UIView *subview in gesture.view.subviews)
{
if (CGRectContainsPoint(subview.frame, location))
{
if (subview != [gesturedSubviews lastObject])
{
[gesturedSubviews addObject:subview];
if (!path)
{
// if the path hasn't be started, initialize it and the shape layer
path = [UIBezierPath bezierPath];
[path moveToPoint:subview.center];
shapeLayer = [[CAShapeLayer alloc] init];
shapeLayer.strokeColor = [UIColor redColor].CGColor;
shapeLayer.fillColor = [UIColor clearColor].CGColor;
shapeLayer.lineWidth = 2.0;
[gesture.view.layer addSublayer:shapeLayer];
}
else
{
// otherwise add this point to the layer's path
[path addLineToPoint:subview.center];
shapeLayer.path = path.CGPath;
}
[UIView animateWithDuration:0.25
delay:0.0
options:UIViewAnimationOptionAutoreverse
animations:^{
subview.alpha = 0.5;
}
completion:^(BOOL finished){
subview.alpha = 1.0;
}];
}
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state == UIGestureRecognizerStateEnded)
{
// assuming the tags are numbers between 0 and 9 (inclusive), we can build the password here
NSMutableString *password = [NSMutableString string];
for (UIView *subview in gesturedSubviews)
[password appendFormat:#"%c", subview.tag + 48];
NSLog(#"Password = %#", password);
// clean up our array of gesturedSubviews
gesturedSubviews = nil;
// clean up the drawing of the path on the screen the user drew
[shapeLayer removeFromSuperlayer];
shapeLayer = nil;
path = nil;
}
}
That yields something like:
You have all sorts of options, but hopefully you now have the building blocks so you can design your own solution.
Forgive me Rob, pure Plagiarism here :) Needed the same code in swift 3.0 :) so I translated this great little example you wrote into swift 3.0.
ViewController.swift
import UIKit
class ViewController: UIViewController {
static let kMargin:CGFloat = 10.0;
override func viewDidLoad()
{
super.viewDidLoad()
// create a container view that all of our subviews for which we want to detect touches are:
let containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - ViewController.kMargin * 2.0
let container = UIView(frame: CGRect(x: ViewController.kMargin, y: ViewController.kMargin, width: containerWidth, height: containerWidth))
container.backgroundColor = UIColor.darkGray
view.addSubview(container)
// now create all of the subviews, specifying a tag for each; and
let cellWidth = (containerWidth - (4.0 * ViewController.kMargin)) / 3.0
for column in 0 ..< 3 {
for row in 0 ..< 3 {
let cell = UIView(frame: CGRect(x: ViewController.kMargin + CGFloat(column) * (cellWidth + ViewController.kMargin), y: ViewController.kMargin + CGFloat(row) * (cellWidth + ViewController.kMargin), width: cellWidth, height: cellWidth))
cell.tag = row * 3 + column;
container.addSubview(cell)
}
}
// finally, create the gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
container.addGestureRecognizer(pan)
}
func handlePan(gesture: UIPanGestureRecognizer)
{
var gesturedSubviews : [UIView] = []
// if we're starting a gesture, initialize our list of subviews that we've gone over
if (gesture.state == .began)
{
gesturedSubviews.removeAll()
}
let location = gesture.location(in: gesture.view)
for subview in (gesture.view?.subviews)! {
if (subview.frame.contains(location)) {
if (subview != gesturedSubviews.last) {
gesturedSubviews.append(subview)
subview.backgroundColor = UIColor.blue
}
}
// finally, when done, let's just log the subviews
// you would do whatever you would want here
if (gesture.state != .recognized)
{
print("We went over:");
for subview in gesturedSubviews {
print(" %d", (subview as AnyObject).tag);
}
// you might as well clean up your static variable when you're done
}
}
}
}
Update: Almost that is; I tried to translate the update too, but my translation missed something and didn't work, so I searched around SO and crafted a similar if slightly different final solution.
import UIKit
import QuartzCore
class ViewController: UIViewController {
static let kMargin:CGFloat = 10.0;
override func viewDidLoad()
{
super.viewDidLoad()
// create a container view that all of our subviews for which we want to detect touches are:
let containerWidth = fmin(self.view.bounds.size.width, self.view.bounds.size.height) - ViewController.kMargin * 2.0
let container = UIView(frame: CGRect(x: ViewController.kMargin, y: ViewController.kMargin, width: containerWidth, height: containerWidth))
container.backgroundColor = UIColor.darkGray
view.addSubview(container)
// now create all of the subviews, specifying a tag for each; and
let cellWidth = (containerWidth - (4.0 * ViewController.kMargin)) / 3.0
for column in 0 ..< 3 {
for row in 0 ..< 3 {
let cell = UIView(frame: CGRect(x: ViewController.kMargin + CGFloat(column) * (cellWidth + ViewController.kMargin), y: ViewController.kMargin + CGFloat(row) * (cellWidth + ViewController.kMargin), width: cellWidth, height: cellWidth))
cell.tag = row * 3 + column;
container.addSubview(cell)
}
}
// finally, create the gesture recognizer
let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan))
container.addGestureRecognizer(pan)
}
// Here's a Swift 3.0 version based on Rajesh Choudhary's answer:
func drawLine(onLayer layer: CALayer, fromPoint start: CGPoint, toPoint end:CGPoint) {
let line = CAShapeLayer()
let linePath = UIBezierPath()
linePath.move(to: start)
linePath.addLine(to: end)
line.path = linePath.cgPath
line.fillColor = nil
line.lineWidth = 8
line.opacity = 0.5
line.strokeColor = UIColor.red.cgColor
layer.addSublayer(line)
}
var gesturedSubviews : [UIView] = []
var startX: CGFloat!
var startY: CGFloat!
var endX: CGFloat!
var endY: CGFloat!
func handlePan(gesture: UIPanGestureRecognizer) {
if (gesture.state == .began)
{
gesturedSubviews = [];
let location = gesture.location(in: gesture.view)
print("location \(location)")
startX = location.x
startY = location.y
}
if (gesture.state == .changed) {
let location = gesture.location(in: gesture.view)
print("location \(location)")
endX = location.x
endY = location.y
drawLine(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:endX, y:endY))
startX = endX
startY = endY
}
if (gesture.state == .ended) {
let location = gesture.location(in: gesture.view)
print("location \(location)")
drawLine(onLayer: view.layer, fromPoint: CGPoint(x: startX, y: startY), toPoint: CGPoint(x:location.x, y:location.y))
}
// now figure out whether:
// (a) are we over a subview; and
// (b) is this a different subview than we last were over
let location = gesture.location(in: gesture.view)
print("location \(location)")
for subview in (gesture.view?.subviews)! {
if subview.frame.contains(location) {
if (subview != gesturedSubviews.last) {
gesturedSubviews.append(subview)
subview.backgroundColor = UIColor.blue
subview.alpha = 1.0
}
}
}
}
}

ZBarReaderView UIView Camera orientation issue

I'm currently developing an iPad application that is using ZBarSDK for reading QR Codes.
I am using ZBarReaderView (NOT UIViewController), so i'm showing the front facing camera in a UIView that is drawn using CGRect (see code below).
My problem is that the camera comes up on it's side within the view. The iPad app will ONLY be developed to work in Landscape mode.
When the UIView comes up now, the image is on it's side and i'm not sure how to fix it. I tried using CGAffineTransform which successfully changes the angle somewhat but how will this handle if the iPad is flipped the other way?
I saw some other posts about this similar issue but no resolution that has worked for me. Worth noting i'm using IOS6 and please remember i'm using ZBarReaderView, so the supportedOrientationsMask is NOT available.
I want the user to see the camera view in the upright position regardless of whether landscape is left or right. Right now though, regardless of which way it is turned, the video is sideways (so I can see myself at 90 degrees to the side). The UIView doesn't change at all when the screen is turned either. I'm a bit lost.
Code:
- (void) viewDidAppear: (BOOL) animated {
ZBarReaderView * readerView = [ZBarReaderView new];
ZBarImageScanner * scanner = [ZBarImageScanner new];
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
[readerView initWithImageScanner:scanner];
readerView.readerDelegate = self;
readerView.tracksSymbols = YES;
readerView.frame = CGRectMake(20,220,230,230);
readerView.torchMode = 0;
readerView.device = [self frontFacingCameraIfAvailable];
[readerView start];
[self.view addSubview: readerView];
}
-(void)relocateReaderPopover:(UIInterfaceOrientation)toInterfaceOrientation {
if (toInterfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
readerView.previewTransform = CGAffineTransformMakeRotation(M_PI_2);
} else if (toInterfaceOrientation == UIInterfaceOrientationLandscapeRight) {
readerView.previewTransform = CGAffineTransformMakeRotation(-M_PI_2);
} else if (toInterfaceOrientation== UIInterfaceOrientationPortraitUpsideDown) {
readerView.previewTransform = CGAffineTransformMakeRotation(M_PI);
} else {
readerView.previewTransform = CGAffineTransformIdentity;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if (interfaceOrientation == UIInterfaceOrientationLandscapeLeft) {
return YES;
} else if (interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
return YES;
} else {
return NO;
}
}
- (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) orient
duration: (NSTimeInterval) duration
{
if (orient == UIInterfaceOrientationLandscapeLeft) {
[readerView willRotateToInterfaceOrientation: orient
duration: duration];
}
if (orient == UIInterfaceOrientationLandscapeRight) {
[readerView willRotateToInterfaceOrientation: orient
duration: duration];
}
}
- (BOOL)shouldAutorotate {
UIInterfaceOrientation orientation = [[UIDevice currentDevice] orientation];
if (orientation == UIInterfaceOrientationLandscapeLeft) {
return YES;
} else if (orientation == UIInterfaceOrientationLandscapeRight) {
return YES;
} else {
return NO;
}
}
-(NSUInteger) supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskLandscape;
}
I got the same issue and resolved it symply !
I just needed to call :
[reader willRotateToInterfaceOrientation: toInterfaceOrientation duration: duration];
within the willRotate... of the view controller that contains the ZbarReaderView.
Okay I got the orientation working now. No idea why it works now but here's the end code for the readerView part:
readerView = [ZBarReaderView new];
ZBarImageScanner * scanner = [ZBarImageScanner new];
[scanner setSymbology: ZBAR_I25
config: ZBAR_CFG_ENABLE
to: 0];
[readerView initWithImageScanner:scanner];
readerView.readerDelegate = self;
readerView.tracksSymbols = YES;
readerView.frame = CGRectMake(20,220,230,230);
readerView.torchMode = 0;
readerView.device = [self frontFacingCameraIfAvailable];
[self relocateReaderPopover:[self interfaceOrientation]];
[readerView start];
[self.view addSubview: readerView];
Notice the only real difference there is this line:
ZBarReaderView * readerView = [ZBarReaderView new];
Changing that line has fixed the initial orientation issue. No idea why but it did. Now I just need to fix the rotation stuff for if the user rotates the iPad.
This worked fine for me:
// ADD: present a barcode reader that scans from the camera feed
ZBarReaderViewController *reader = [ZBarReaderViewController new];
reader.readerDelegate = self;
//reader.supportedOrientationsMask = ZBarOrientationMaskAll;
ScanOverlay *overlayController = [[ScanOverlay alloc] initWithNibName:#"ScanOverlay" bundle:nil];
reader.cameraOverlayView = overlayController.view;
ZBarImageScanner *scanner = reader.scanner;
// TODO: (optional) additional reader configuration here
reader.supportedOrientationsMask = ZBarOrientationMask(UIInterfaceOrientationLandscapeRight||UIInterfaceOrientationLandscapeLeft);
reader.wantsFullScreenLayout = YES;
reader.showsZBarControls = NO; //If we don't set this to NO, the overlay may not display at all
reader.tracksSymbols = YES;
//To support Landscape orientation
UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
if (UIDeviceOrientationLandscapeLeft == orientation) {
//Rotate 90
reader.cameraViewTransform = CGAffineTransformMakeRotation (3*M_PI/2.0);
} else if (UIDeviceOrientationLandscapeRight == orientation) {
//Rotate 270
reader.cameraViewTransform = CGAffineTransformMakeRotation (M_PI/2.0);
}

How to center UIImageView in ScrollView (Zooming)

I'm trying to zooming UIImageView in UIScrollView. And i've got this:
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return imageView;
}
-(void)scrollViewDidZoom:(UIScrollView *)scrollView {
[imageView setCenter:CGPointMake(scrollView.center.x, scrollView.center.y)];
}
-(void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale {
}
Problem is: When i'm zooming out image it's centered, but when i'm zooming in, image is shifted to left up corner.
Where is problem with my code?
Answer is remove all from scrollViewDidZoom: and add:
[self centerScrollViewContent];
Method implementation:
- (void)centerScrollViewContents {
CGSize boundsSize = self.scrollView.bounds.size;
CGRect contentsFrame = self.containerView.frame;
if (contentsFrame.size.width < boundsSize.width) {
contentsFrame.origin.x = (boundsSize.width - contentsFrame.size.width) / 2.0f;
} else {
contentsFrame.origin.x = 0.0f;
}
if (contentsFrame.size.height < boundsSize.height) {
contentsFrame.origin.y = (boundsSize.height - contentsFrame.size.height) / 2.0f;
} else {
contentsFrame.origin.y = 0.0f;
}
self.containerView.frame = contentsFrame;
}

iOS: Multiple intersecting views

I am making a day view calendar just like the native iPhone calendar. I am trying to position the tiles the same as in the native calendar, side by side, if they are the same size and same time.
However, I can only figure out how to do it to 2 tiles and not multiple tiles. In the attached image I have 4 tiles. One that expands slightly into the other 3. I then have the first tile on the far left and the second tile just after the first one. Now I need to figure out how to add the additional tiles?
How would I do this for more than 2 tiles?
About the image: If you can't see it the 3rd tile is ontop of the 2nd tile (you can see it is a bit darker since they are on top of each other.
- (void)layoutSubviews
{
// Set the main
for (UIView *view in self.subviews) {
APCalendarDayTile *tile = (APCalendarDayTile *)view;
CGFloat startPos = [APCalendarCurrentDayView yAxisForTime:[APCalendarCurrentDayView minutesToTime:tile.appointment.startDate]];
CGFloat endPos = [APCalendarCurrentDayView yAxisForTime:[APCalendarCurrentDayView minutesToTime:tile.appointment.endDate]];
tile.frame = CGRectMake(kLeftSideBuffer, startPos, (self.bounds.size.width - kLeftSideBuffer) , endPos - startPos);
tile.backgroundColor = [UIColor colorWithHexString:tile.appointment.appointmentColor];
}
for (UIView *view in self.subviews) {
APCalendarDayTile *tile = (APCalendarDayTile *)view;
if ([self viewIntersectsWithAnotherView:tile]) {
}
}
}
- (BOOL)viewIntersectsWithAnotherView:(UIView*)selectedView{
NSArray *subViewsInView=[self subviews];// I assume self is a subclass
// of UIViewController but the view can be
//any UIView that'd act as a container
//for all other views.
for (UIView *theView in subViewsInView){
if (![selectedView isEqual:theView]) {
if(CGRectIntersectsRect(selectedView.frame, theView.frame)) {
if ((selectedView.frame.origin.y == theView.frame.origin.y) && (selectedView.frame.size.height == theView.frame.size.height)) {
if (theView.frame.size.width == self.bounds.size.width - kLeftSideBuffer) {
theView.frame = CGRectMake(theView.frame.origin.x, selectedView.frame.origin.y, theView.frame.size.width / 2, selectedView.frame.size.height);
}
selectedView.frame = CGRectMake(theView.frame.origin.x + theView.frame.size.width, selectedView.frame.origin.y, theView.frame.size.width, selectedView.frame.size.height);
return YES;
}
}
}
}
return NO;
}
It appears that your test
if ((selectedView.frame.origin.y == theView.frame.origin.y) && (selectedView.frame.size.height == theView.frame.size.height))
Is only applied to views of equal y origin and height. I would solve this problem using the following pseudo code:
initialize an empty arranged subviews array
initialize a nil previous subview
for every subview
if the subview intersects with the previous subview
ensure the subview and the previous subview are added to the arranged subviews array
else if the arranged subviews array is not empty
arrange the subviews in the array across the width of their superview
empty the arranged subview array
Ok,
I sorta took SaltyMule's approach however, his pseudo code didn't make sense in the if / else.
- (void)layoutSubviews
{
// Set the main
for (UIView *view in self.subviews) {
APCalendarDayTile *tile = (APCalendarDayTile *)view;
CGFloat startPos = [APCalendarCurrentDayView yAxisForTime:[APCalendarCurrentDayView minutesToTime:tile.appointment.startDate]];
CGFloat endPos = [APCalendarCurrentDayView yAxisForTime:[APCalendarCurrentDayView minutesToTime:tile.appointment.endDate]];
tile.frame = CGRectMake(kLeftSideBuffer, startPos, (self.bounds.size.width - kLeftSideBuffer) , endPos - startPos);
tile.backgroundColor = [UIColor colorWithHexString:tile.appointment.appointmentColor];
}
[sameTimeAppointments removeAllObjects];
for (UIView *view in self.subviews) {
APCalendarDayTile *tile = (APCalendarDayTile *)view;
if ([self viewIntersectsWithAnotherView:tile]) {
if ([sameTimeAppointments objectForKey:[NSString stringWithFormat:#"%f", tile.frame.origin.y]] != nil) {
NSMutableArray *tempArray = [[sameTimeAppointments objectForKey:[NSString stringWithFormat:#"%f", tile.frame.origin.y]] mutableCopy];
[tempArray addObject:tile];
[sameTimeAppointments setValue:tempArray forKey:[NSString stringWithFormat:#"%f", tile.frame.origin.y]];
} else {
[sameTimeAppointments setValue:[NSMutableArray arrayWithObject:tile] forKey:[NSString stringWithFormat:#"%f", tile.frame.origin.y]];
}
}
}
for (NSString *currentDict in sameTimeAppointments) {
NSArray *currentAppointments = [sameTimeAppointments objectForKey:currentDict];
float tileWidth = ((self.frame.size.width - kLeftSideBuffer) / [currentAppointments count]);
for (int i = 0; i < [currentAppointments count]; i++) {
APCalendarDayTile *tile = [currentAppointments objectAtIndex:i];
float xPos = 0.0 + kLeftSideBuffer;
if (i != 0) {
xPos = (((APCalendarDayTile *)[currentAppointments objectAtIndex:i - 1]).frame.origin.x + tileWidth);
}
tile.frame = CGRectMake(xPos, tile.frame.origin.y, tileWidth, tile.frame.size.height);
[self bringSubviewToFront:tile];
}
}
}
- (BOOL)viewIntersectsWithAnotherView:(UIView*)selectedView{
NSArray *subViewsInView=[self subviews];// I assume self is a subclass
// of UIViewController but the view can be
//any UIView that'd act as a container
//for all other views.
for (UIView *theView in subViewsInView){
if (![selectedView isEqual:theView]) {
if(CGRectIntersectsRect(selectedView.frame, theView.frame)) {
if ((selectedView.frame.origin.y == theView.frame.origin.y) && (selectedView.frame.size.height == theView.frame.size.height)) {
return YES;
}
}
}
}
return NO;
}