开发者

Effect like Interface Builder connection lines on iPhone

Hi I'd like little bit of help on something. In my app, I have a UITableView which is populated with custom cells that represent images. (i.e. selecting a row displays a picture in an image view).

What I would like to do, is have an icon in the custom cell that I could drag to one of a series of image views. Similar to the way you can drag a line in IB to set connections. Once the user releases their finger I will have it check what part of the screen they released it and if it is one one of these rects that represent the picture frames, it will populate the picture frame with the image and the line will disappear.

I have never drawn lines in my app before so thats 开发者_Go百科not something I know how to do (so im just looking for a link to a tutorial or class definition) and second, what problems will I have since the start point of the line is in a UITableViewCell and the end point is in the main view?


I have actually done this before, so I can give you the exact code :D

This is only the drawing part, you implement the touch events (in a separate class, otherwise remove the self.userInteractionEnabled = NO; in .m file

The BOOL dragged tells the LineView if the line should be drawn.

LineView.h

#import <UIKit/UIKit.h>

@interface LineView : UIView 
{
    CGPoint start;
    CGPoint end;

    BOOL dragged;
}

@property CGPoint start, end;
@property BOOL dragged;

@end

LineView.m

#import "LineView.h"

@implementation LineView

@synthesize start, end, dragged;

- (id)initWithFrame:(CGRect)frame 
{
    if (self = [super initWithFrame: frame])
    {
        self.userInteractionEnabled = NO;
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

#pragma mark Setters
-(void) setStart: (CGPoint) s
{
    start = s;
    [self setNeedsDisplay];
}

-(void) setEnd: (CGPoint) e
{
    end = e;
    [self setNeedsDisplay];
}

#define LINE_COLOR   [UIColor redColor]
#define CIRCLE_COLOR [UIColor redColor]

#define LINE_WIDTH    5
#define CIRCLE_RADIUS 10

- (void)drawRect:(CGRect)rect 
{
    CGContextRef c = UIGraphicsGetCurrentContext();

    if(dragged) {
        [LINE_COLOR setStroke];
        CGContextMoveToPoint(c, start.x, start.y);
        CGContextAddLineToPoint(c, end.x, end.y);        
        CGContextSetLineWidth(c, LINE_WIDTH); 
        CGContextClosePath(c);
        CGContextStrokePath(c);

        [CIRCLE_COLOR setFill];
        CGContextAddArc(c, start.x, start.y, CIRCLE_RADIUS, 0, M_PI*2, YES);
        CGContextClosePath(c);
        CGContextFillPath(c);

        CGContextAddArc(c, end.x, end.y, CIRCLE_RADIUS, 0, M_PI*2, YES);
        CGContextClosePath(c);
        CGContextFillPath(c);
    }
}

- (void)dealloc 
{
    [super dealloc];
}

@end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜