如何设置在自定义视图中绘制一些图像并拖放它们

时间:2009-12-09 13:16:57

标签: cocoa draggable

我正在写一个Cocoa应用程序。我写了一个可以拖放一个图像的代码。但现在我需要通过双击和D& D来绘制几个图像。每次双击 - 新图像,每次点击现有图像 - 都会启动D& D.问题在于实现。我无法想象一种简单的实现方式。任何人都可以提出解决方案吗?

感谢。

#import "DotView.h"


@implementation DotView

- (id)initWithFrame:(NSRect)frame 
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        center.x = center.y = 100.0;
    }
    return self;
}
- (void)drawRect:(NSRect)rect {
        NSRect bounds = [self bounds];
        [[NSColor whiteColor] set];
        NSRectFill(bounds);

        [[NSGraphicsContext currentContext]
         setImageInterpolation: NSImageInterpolationHigh];

        NSSize viewSize  = [self bounds].size;
        NSSize imageSize = { 50, 40 };

        NSPoint imageOrigin = center;
        imageOrigin.x -= imageSize.width  * 0.50;
        imageOrigin.y -= imageSize.height * 0.50;


        NSRect destRect;
        destRect.origin = imageOrigin;
        destRect.size = imageSize;

        NSString * file = @"/Users/classuser/Desktop/ded.jpg";
        NSImage * image = [[NSImage alloc] initWithContentsOfFile:file];
        [image setFlipped:NO];

        [image drawInRect: destRect
                 fromRect: NSZeroRect
                operation: NSCompositeSourceOver
                 fraction: 1.0];

        NSBezierPath * path = [NSBezierPath bezierPathWithRect:destRect];
        }
-(void)mouseDown:(NSEvent*)event
{
    NSPoint point = [event locationInWindow];
        if(center.x<point.x+25 && center.x>point.x-25)
            if(center.y<point.y+20 && center.y>point.y-20)
                center = [self convertPoint:point fromView:nil];
}

- (void) mouseDragged:(NSEvent*)event {

    [self mouseDown:event];
    [self setNeedsDisplay:YES];

}


@end

1 个答案:

答案 0 :(得分:0)

读:

Cocoa Drawing Guide

View Programming Guide for Cocoa

Drag and Drop Programming Topics for Cocoa

一旦你阅读了这些内容,就会提出更具针对性的问题 - 这有点过于宽泛而无法简单回答。