2

アプリケーションに nsscroll ビューがあり、nsscrollview のサブクラスを作成して nsgradient を追加しましたが、機能しません。これは実装ファイルのコードです。

#import "scrollview.h"
@implementation scrollview
@synthesize startingColor;
@synthesize endingColor;
@synthesize angle;

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
        [self setStartingColor:[NSColor colorWithCalibratedRed:0.941 green:0.941 blue:0.941 alpha:1]];
        [self setEndingColor:[NSColor colorWithCalibratedRed:0.6588 green:0.6588 blue:0.6588 alpha:1]];


        [self setAngle:90];
    }
    return self;
}

- (void)drawRect:(NSRect)rect {

    NSBezierPath* roundRectPath = [NSBezierPath bezierPathWithRoundedRect: [self bounds] xRadius:10 yRadius:10]; 
    [roundRectPath addClip];
    if (endingColor == nil || [startingColor isEqual:endingColor]) {
        // Fill view with a standard background color
        [startingColor set];
        NSRectFill(rect);
    }
    else {
        // Fill view with a top-down gradient
        // from startingColor to endingColor
        NSGradient* aGradient = [[NSGradient alloc]
                                 initWithStartingColor:startingColor
                                 endingColor:endingColor];
        [aGradient drawInRect:[self bounds] angle:angle];
    }
}
4

1 に答える 1

4

最初のステップは、グラデーションを描画するカスタム NSView サブクラスを作成することです。

GradientBackgroundView.h:

@interface GradientBackgroundView : NSView
{}
@end

GradientBackgroundView.m:

#import "GradientBackgroundView.h"
@implementation GradientBackgroundView    
- (void) drawRect:(NSRect)dirtyRect
{
    NSGradient *gradient = [[[NSGradient alloc] initWithStartingColor:[NSColor redColor] endingColor:[NSColor greenColor]] autorelease];
    [gradient drawInRect:[self bounds] angle:90];
}
@end

次のステップは、スクロール ビューのドキュメント ビューを (プレーンな NSView ではなく) このクラスのインスタンスにすることです。

IB でスクロール ビューをダブルクリックし、Identity ペインで Class を GradientBackgroundView に設定します。

この時点から、物事はほとんど標準的な方法で処理されます。サブビューをドキュメント ビューに追加したり、サイズを変更したりできます。スクリーンショットは次のとおりです。 グラデーションの背景

于 2011-05-13T17:04:48.843 に答える