Draw only resized area of NSView - objective-c

I'm trying to draw an NSView efficiently, even when resizing. According to the docs for -drawRect:, I can use -getRectsBeingDrawn:count: to figure out what exactly needs to be redrawn and only redraw that. Furthermore, if I want to have live-resizing preserve content, I should return YES from -preservesContentDuringLiveResize and override -setFrameSize: and use -getRectsExposedDuringLiveResize:count: to determine what to mark as needing display. But while live-resizing the window, inside -drawRect: the -getRectsBeingDrawn:count: method still returns the entire bounds of the NSView rather than just the newly exposed part of the view. I confirm this using the NSView subclass below (auto-sized to always fill the window) and by dragging the window's bottom edge downward.
- (void) drawRect:(NSRect)dirtyRect {
const NSRect* rects;
NSInteger count;
[self getRectsBeingDrawn:&rects count:&count];
for (int i = 0; i < count; i++) {
NSRect r = rects[i];
[[[NSColor greenColor] colorWithAlphaComponent:0.5] drawSwatchInRect:r];
}
}
- (BOOL) preservesContentDuringLiveResize {
return YES;
}
- (BOOL) isOpaque {
return YES;
}
- (void) setFrameSize:(NSSize)newSize {
[super setFrameSize:newSize];
if ([self inLiveResize]) {
NSRect rects[4];
NSInteger count;
[self getRectsExposedDuringLiveResize:rects count:&count];
for (int i = 0; i < count; i++) {
NSRect r = rects[i];
[self setNeedsDisplayInRect:r];
}
}
else {
[self setNeedsDisplay:YES];
}
}

Related

CGContextFillRects: CGRect* not working. Assigned CGRect items do not get saved

I am trying to save an array of CGRect to use with CGContextFillRects but the CGRect variables I assign to my minorPlotLines array don't seem to get saved. By the time the object here draws itself minorPlotLines is empty! Does anyone know what is going on?
#interface GraphLineView () {
int numberOfLines;
CGRect *minorPlotLines;
}
#end
#implementation GraphLineView
- (instancetype) initWithFrame: (CGRect) frame {
self = [super initWithFrame:frame];
if (self) {
// Init code
[self setupView];
}
return self;
}
- (instancetype) initWithCoder: (NSCoder *) aDecoder {
if(self == [super initWithCoder:aDecoder]){
[self setupView];
}
return self;
}
- (void) dealloc {
free(minorPlotLines);
}
- (void) setupView {
numberOfLines = 40;
minorPlotLines = malloc(sizeof(struct CGRect)*40);
for(int x = 0; x < numberOfLines; x += 2){
//minorPlotLines[x] = *(CGRect*)malloc(sizeof(CGRect));
minorPlotLines[x] = CGRectMake(x*(self.frame.size.width/numberOfLines), 0, 2, self.frame.size.height);
// minorPlotLines[x+1] = *(CGRect*)malloc(sizeof(CGRect));
minorPlotLines[x+1] = CGRectMake(0, x*(self.frame.size.height/numberOfLines), self.frame.size.width, 2);
}
[self setNeedsDisplay];
}
- (void) drawRect:(CGRect)rect {
// Drawing code
[super drawRect:rect];
for(int x = 0; x < numberOfLines; x += 2){
NSLog(#"R %d = %f", x, minorPlotLines[x].origin.x);
NSLog(#"R %d = %f", x+1, minorPlotLines[x+1].origin.y);
}
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [[UIColor yellowColor] CGColor]);
CGContextFillRects(context, minorPlotLines, numberOfLines);
}
I tried pulling your code (to construct the contents of minorPlotLines and later read the contents back out) into another project, and it does seem to preserve the contents just fine, so your basic code itself seems sound.
I would check to make sure that you actually have a non-zero frame at the time you're constructing the array minorPlotLines (i.e. in -setupView). It's quite common for early-stage UI class loading callbacks to be called at a time when your class is only partially constructed (e.g. UIViewController class' callback -viewDidLoad), leaving you no choice but to defer certain decisions until later in the loading process. Layout in particular happens relatively late in the game, and since your -setupView method is called right within an -init method I'm guessing the framework hasn't provided any layout to your class yet, and hence it has no usable frame (i.e. your frame is effectively equivalent to CGRectZero).

NSView Instantiation and Get Its Values with Identifier

I have a subclass of NSView named clickView as follows.
// clickView.h
#interface clickView : NSView {
BOOL onOff;
}
- (BOOL)getOnOff;
// clickView.m
- (BOOL)getOnOff {
return onOff;
}
- (void)mouseDown:(NSEvent *)event {
if (onOff) {
onOff = NO;
} else {
onOff = YES;
}
[self setNeedsDisplay:YES];
NSLog(#"%#",self.identifier);
}
It utilizes its drawRect method (, which is not shown here,) to fill the rectangle with a color if the user clicks on it. And it uses a boolean value (onOff) to see if it's been clicked on. Now, switching to AppleDelegate, I instantiate this NSView subclass as follows.
// AppDelegate.m
- (IBAction)create4Clicked:(id)sender {
NSInteger rowCount = 10;
NSInteger colCount = 10;
NSInteger k = 1;
for (NSInteger i2 = 0; i2 < rowCount; i2 ++) {
for (NSInteger i3 = 0; i3 < colCount; i3 ++) {
NSView *view = [[clickView alloc] initWithFrame:NSMakeRect(50+i2*10,50+i3*10,10,10)];
[view setIdentifier:[NSString stringWithFormat:#"%li",k]];
[view1 addSubview:view]; // view1 is NSView that's been created with Interface Builder
k++;
}
}
}
So I now have 100 squares displayed on view1 (NSView). If I click on any of the squares, I do get its identifier. (See 'mouseDown.') Now, what I need to figure out is how to tell which square has its 'onOff' set to YES (or NO).
Thank you for your help.
A. First off all:
Probably you are new to Cocoa and Objective-C.
a. Why don't you use buttons?
b. onOff is obviously a property. Why don't you use declared properties?
B. To your Q:
You can retrieve the views with a specific state by asking the superview for its subviews and then filter them with a predicate:
NSPredicate *clickedPredicate = [NSPredicate predicateWithFormat:#"onOff == %d", YES];
NSArray* clickViews = [view1 subviews]; // Returns all subviews
clickViews = [clickViews filteredArrayUsingPredicate:clickedPredicate]; // On-views
But you should think about storing the state outside the views. What is your app for?

finding locations of subview in superview

Hello i have superview in which i have many UIImageViews.I have added UIPanGesture to the SuperView which is 'View.m' in my case. I need to get the reference or in others words object of that UIImageView(subview) when user drags over it in superview.Also if this can be done with 'hittest' then let me know how to use it in gestureHandler and as hittest returns UIView , how i can convert UiView to UIImageView. Here is my code
//
// View.m
// PuzzleGame
//
// Created by Noman Khan on 8/29/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "View.h"
#define noOfRows 5
#define noOfCols 4
#implementation View
#synthesize imageArray;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)initImageView {
int x = 1;
int y = 1;
// int width = 190;
// int height = 198;
int width = sizeOfRows;
int height = sizeOfCols;
UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(x,y,width-10,height+5)];
imgView.image=[UIImage imageNamed:#"iceage_01.png"];
[self addSubview:imgView];
x=x+(width-9);
y=y+(sizeOfCols+9);
UIImageView *imgView1=[[UIImageView alloc]initWithFrame:CGRectMake(x,y,width-10,height+5)];
imgView1.image=[UIImage imageNamed:#"iceage_02.png"];
[self addSubview:imgView1];
- (void)drawRect:(CGRect)rect
{
imageArray=[[NSArray alloc]initWithObjects:[UIImage imageNamed:#"iceage_01.png"],[UIImage imageNamed:#"iceage_02.png"],[UIImage imageNamed:#"iceage_03.png"],[UIImage imageNamed:#"iceage_04.png"],[UIImage imageNamed:#"iceage_05.png"],[UIImage imageNamed:#"iceage_06.png"],[UIImage imageNamed:#"iceage_07.png"],[UIImage imageNamed:#"iceage_08.png"],[UIImage imageNamed:#"iceage_09.png"],[UIImage imageNamed:#"iceage_10.png"],[UIImage imageNamed:#"iceage_11.png"],[UIImage imageNamed:#"iceage_12.png"],[UIImage imageNamed:#"iceage_13.png"],[UIImage imageNamed:#"iceage_14.png"],[UIImage imageNamed:#"iceage_15.png"],[UIImage imageNamed:#"iceage_16.png"],[UIImage imageNamed:#"iceage_17.png"],[UIImage imageNamed:#"iceage_18.png"],[UIImage imageNamed:#"iceage_19.png"],[UIImage imageNamed:#"iceage_20.png"], nil];
CGContextRef content=UIGraphicsGetCurrentContext();
CGContextSetLineWidth(content, 2);
CGContextSetStrokeColorWithColor(content, [UIColor whiteColor].CGColor);
int totalWidth=self.frame.size.width;
int totalHeight=self.frame.size.height;
sizeOfRows=totalHeight/noOfRows;
sizeOfCols=totalWidth/noOfCols;
//making rows
int x = 0,y = 0;
for (int i=0; i<noOfRows+1; i++) {
CGContextMoveToPoint(content, x, y);
CGContextAddLineToPoint(content, 1000, y);
CGContextStrokePath(content);
//y=y+200;
y=y+sizeOfRows;
}
//making colums
x=0,y=0;
for (int i=0; i<noOfCols+1; i++) {
CGContextMoveToPoint(content, x, y);
CGContextAddLineToPoint(content, x, 1000);
CGContextStrokePath(content);
//x=x+192;
x=x+sizeOfCols;
}
[self initImageView];
UIPanGestureRecognizer *panGesture=[[UIPanGestureRecognizer alloc]initWithTarget:self action:#selector(panHandler:)];
[self addGestureRecognizer:panGesture];
// CGContextMoveToPoint(content, 20, 20);
// CGĂ„ContextAddLineToPoint(content, 50, 50);
//
// CGContextStrokePath(content);
}
- (void)panHandler:(UIGestureRecognizer *)sender{
CGPoint point=[sender locationInView:self];
if (sender.state == UIGestureRecognizerStateBegan) {
NSLog(#"BEgin");
UIView *v=[[UIView alloc]initWithFrame:CGRectMake(75, 75, 100, 100)];
v = [self hitTest:point withEvent:nil];
// UIImageView *imv=(UIImageView*)v;
[self addSubview:v];
}
if (sender.state == UIGestureRecognizerStateChanged) {
NSLog(#"moved");
}
if (sender.state == UIGestureRecognizerStateEnded) {
NSLog(#"end");
}
// NSLog(#"In Pan Handler");
}
#end
Yes you can use hittest.
Hittest works in recursive fashion, below are some important points about hittest.
1. It calls pointInside:withEvent: of self
2. If it ,hitTest:withEvent:, returns nil. your view hierarchy is end. you dont have further views.
3. If it returns YES, the message is passed to subviews, it starts from the top-level subview, and continues to other views until a subview returns a non-nil object or all subviews receive the message.
4. If no nil object is returned nil, the self is returned
UIImageView is the subclass of UIView so you can cast your hittest returned view to UIImageView:
UIImageView *imageView = (UIImageView *)[[UIView alloc]initWithFrame:CGRectMake(75, 75, 100, 100)];
You can use Tag property of view for much better handling.

Why does an empty UIScrollView have two subviews?

I have a need to calculate the height of of my content within a UIScrollView.
I dropped an empty UIScrollView into the XCode Storyboard, gave it a custom class with this code:
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super initWithCoder:decoder];
if (self) {
int i;
for (i = 0; i < [self.subviews count]; i++) {
UIView *view =[self.subviews objectAtIndex:i];
NSLog(#"sub view %# x:%f, y:%f, w:%f, h:%f", [view class], view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height);
}
}
return self;
}
With an empty UIScrollView this is what logs to the console:
sub view UIImageView x:233.000000, y:121.000000, w:7.000000, h:7.000000
sub view UIImageView x:233.000000, y:121.000000, w:7.000000, h:7.000000
What are those images? They throw off my calculations because they are always below my content.
They're the scrollbars (or scroll indicators, if you prefer.) One is horizontal and the other is vertical.

NSScrollView infinite / endless scroll | subview reuse

I'm searching for a way to implement something like reusable cells for UI/NSTableView but for NSScrollView. Basically I want the same like the WWDC 2011 video "Session 104 - Advanced Scroll View Techniques" but for Mac.
I have several problems realizing this. The first: NSScrollView doesn't have -layoutSubviews. I tried to use -adjustScroll instead but fail in setting a different contentOffset:
- (NSRect)adjustScroll:(NSRect)proposedVisibleRect {
if (proposedVisibleRect.origin.x > 600) {
// non of them work properly
// proposedVisibleRect.origin.x = 0;
// [self setBoundsOrigin:NSZeroPoint];
// [self setFrameOrigin:NSZeroPoint];
// [[parentScrollView contentView] scrollPoint:NSZeroPoint];
// [[parentScrollView contentView] setBoundsOrigin:NSZeroPoint];
}
return proposedVisibleRect;
}
The next thing I tried was to set a really huge content view with a width of millions of pixel (which actually works in comparison to iOS!) but now the question is, how to install a reuse-pool?
Is it better to move the subviews while scrolling to a new position or to remove all subviews and insert them again? and how and where should I do that?
As best I can tell, -adjustScroll: is not where you want to tap into the scrolling events because it doesn't get called universally. I think -reflectScrolledClipView: is probably a better hookup point.
I cooked up the following example that should hit the high points of one way to do a view-reusing scroll view. For simplicity, I set the dimensions of the scrollView's documentView to "huge", as you suggest, rather than trying to "fake up" the scrolling behavior to look infinite. Obviously drawing the constituent tile views for real is up to you. (In this example I created a dummy view that just fills itself with red with a blue outline to convince myself that everything was working.) It came out like this:
// For the header file
#interface SOReuseScrollView : NSScrollView
#end
// For the implementation file
#interface SOReuseScrollView () // Private
- (void)p_updateTiles;
#property (nonatomic, readonly, retain) NSMutableArray* p_reusableViews;
#end
// Just a small diagnosting view to convince myself that this works.
#interface SODiagnosticView : NSView
#end
#implementation SOReuseScrollView
#synthesize p_reusableViews = mReusableViews;
- (void)dealloc
{
[mReusableViews release];
[super dealloc];
}
- (NSMutableArray*)p_reusableViews
{
if (nil == mReusableViews)
{
mReusableViews = [[NSMutableArray alloc] init];
}
return mReusableViews;
}
- (void)reflectScrolledClipView:(NSClipView *)cView
{
[super reflectScrolledClipView: cView];
[self p_updateTiles];
}
- (void)p_updateTiles
{
// The size of a tile...
static const NSSize gGranuleSize = {250.0, 250.0};
NSMutableArray* reusableViews = self.p_reusableViews;
NSRect documentVisibleRect = self.documentVisibleRect;
// Determine the needed tiles for coverage
const CGFloat xMin = floor(NSMinX(documentVisibleRect) / gGranuleSize.width) * gGranuleSize.width;
const CGFloat xMax = xMin + (ceil((NSMaxX(documentVisibleRect) - xMin) / gGranuleSize.width) * gGranuleSize.width);
const CGFloat yMin = floor(NSMinY(documentVisibleRect) / gGranuleSize.height) * gGranuleSize.height;
const CGFloat yMax = ceil((NSMaxY(documentVisibleRect) - yMin) / gGranuleSize.height) * gGranuleSize.height;
// Figure out the tile frames we would need to get full coverage
NSMutableSet* neededTileFrames = [NSMutableSet set];
for (CGFloat x = xMin; x < xMax; x += gGranuleSize.width)
{
for (CGFloat y = yMin; y < yMax; y += gGranuleSize.height)
{
NSRect rect = NSMakeRect(x, y, gGranuleSize.width, gGranuleSize.height);
[neededTileFrames addObject: [NSValue valueWithRect: rect]];
}
}
// See if we already have subviews that cover these needed frames.
for (NSView* subview in [[[self.documentView subviews] copy] autorelease])
{
NSValue* frameRectVal = [NSValue valueWithRect: subview.frame];
// If we don't need this one any more...
if (![neededTileFrames containsObject: frameRectVal])
{
// Then recycle it...
[reusableViews addObject: subview];
[subview removeFromSuperview];
}
else
{
// Take this frame rect off the To-do list.
[neededTileFrames removeObject: frameRectVal];
}
}
// Add needed tiles from the to-do list
for (NSValue* neededFrame in neededTileFrames)
{
NSView* view = [[[reusableViews lastObject] retain] autorelease];
[reusableViews removeLastObject];
if (nil == view)
{
// Create one if we didnt find a reusable one.
view = [[[SODiagnosticView alloc] initWithFrame: NSZeroRect] autorelease];
NSLog(#"Created a view.");
}
else
{
NSLog(#"Reused a view.");
}
// Place it and install it.
view.frame = [neededFrame rectValue];
[view setNeedsDisplay: YES];
[self.documentView addSubview: view];
}
}
#end
#implementation SODiagnosticView
- (void)drawRect:(NSRect)dirtyRect
{
// Draw a red tile with a blue border.
[[NSColor blueColor] set];
NSRectFill(self.bounds);
[[NSColor redColor] setFill];
NSRectFill(NSInsetRect(self.bounds, 2,2));
}
#end
This worked pretty well as best I could tell. Again, drawing something meaningful in the reused views is where the real work is here.
Hope that helps.