[Cocoa]_[初级]_[自定义的界面上绘制图片]

本文介绍如何通过创建NSView的子类实现自定义视图,包括设置图片、绘制矩形、线条等元素,并展示了如何在应用控制器中显示图片。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建一个NSView的子类. 然后根据需要创建自定义的view 来完成自定义画图和事件响应.

头文件:StretchView.h

#import <Cocoa/Cocoa.h>

@interface StretchView : NSView
{
    NSBezierPath *path;
    NSImage *image;
}
-(void) setImage:(NSImage *) newImage;
@end

源文件:StretchView.m
#import "StretchView.h"
@implementation StretchView
-(void) setImage:(NSImage *)newImage
{
    [newImage retain];
    [image release];
    image = newImage;
    [self setNeedsDisplay:YES];
}

-(id) initWithFrame:(NSRect)frameRect
{
    [path closePath];
    return self;
}

-(void) drawRect:(NSRect) rect
{
    NSRect bounds = [self bounds];
    [[NSColor greenColor] set];
    [NSBezierPath fillRect:bounds];
    [[NSColor whiteColor] set];
    [path stroke];
    
    NSBezierPath *path = [NSBezierPath bezierPath];
    [path setLineWidth:2];
    NSPoint startPoint = {0, 20};
    NSPoint endPoint = { 100,20};
    
    NSPoint secondPoint = {0,130};
    NSPoint secondEndPoint ={100,130};
    [path moveToPoint:startPoint];
    [path lineToPoint:endPoint];
    [path moveToPoint:secondPoint];
    [path lineToPoint:secondEndPoint];
    [[NSColor brownColor] set];
  
    [path stroke];
    
    
    NSRect r = NSMakeRect(0,1,100,150);
    NSBezierPath *bp = [NSBezierPath bezierPathWithRect:r];
    NSColor *color = [NSColor blueColor];
    NSString *str = @" 11.png";
    [str drawInRect:r withAttributes:NULL];
    
    [color set];
    [bp stroke];
    
    NSRect downRect = NSMakeRect(0, 1, 100, 20);
    NSString *downString =@" # 1";
    [downString drawInRect:downRect withAttributes:nil];
   
    if(image)
    {
        NSRect imageRect;
        imageRect.origin = NSZeroPoint;
        imageRect.size = [image size];
        NSRect drawingRect = [self currentRect];
        [image drawInRect:drawingRect
                 fromRect:imageRect
                operation:NSCompositeSourceOver
                 fraction:1.0];
    }
}

-(void) dealloc
{
    [path release];
    [image release];
    [super dealloc];
}
-(NSRect) currentRect
{
    return NSMakeRect(0, 0, 400, 400);
}
@end

头文件:AppController.h

#import <Cocoa/Cocoa.h>
@class StretchView;

@interface AppController : NSObject
{
    IBOutlet StretchView *stretchView;
}
-(void)showImage;
@end
源文件:AppController.m

#import "AppController.h"
#import "StretchView.h"

@implementation AppController

-(void) showImage
{
   
        NSString *path = @"Users/picture/11.png";
        NSImage *image = [[NSImage alloc] initWithContentsOfFile:path];
        
        [stretchView setImage:image];
        [image release];
    
}

@end




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值