NSShadow con una subclase NSButton
-
21-09-2019 - |
Pregunta
Aquí está mi código:
- (void)drawRect:(NSRect)dirtyRect {
// Drawing code here.
// Create the Gradient
NSGradient *fillGradient = nil;
if (mouseIsDown)
fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedRed:0.868 green:0.873 blue:0.868 alpha:1.000] endingColor:[NSColor colorWithCalibratedRed:0.687 green:0.687 blue:0.687 alpha:1.000]];
else
fillGradient = [[NSGradient alloc] initWithStartingColor:[NSColor colorWithCalibratedRed:0.687 green:0.687 blue:0.687 alpha:1.000] endingColor:[NSColor colorWithCalibratedRed:0.868 green:0.873 blue:0.868 alpha:1.000]];
// Add The Text
NSDictionary *att = nil;
NSMutableParagraphStyle *style =
[[NSParagraphStyle defaultParagraphStyle] mutableCopy];
[style setLineBreakMode:NSLineBreakByWordWrapping];
[style setAlignment:NSLeftTextAlignment];
att = [[NSDictionary alloc] initWithObjectsAndKeys:
style, NSParagraphStyleAttributeName,
[NSColor blackColor],
NSForegroundColorAttributeName, nil];
[style release];
// Create the path
aPath = [[NSBezierPath bezierPath] retain];
[aPath moveToPoint:NSMakePoint(10.0, 0.0)];
[aPath lineToPoint:NSMakePoint(70.0, 0.0)];
[aPath lineToPoint:NSMakePoint(70.0, 23.0)];
[aPath lineToPoint:NSMakePoint(10.0, 23.0)];
[aPath lineToPoint:NSMakePoint(0.0, 10.0)];
NSShadow *shadow = [[NSShadow alloc] init];
[shadow setShadowColor:[NSColor blackColor]];
[shadow setShadowOffset:NSMakeSize(0, 0)];
[shadow setShadowBlurRadius:5];
[shadow set];
NSRect rect;
rect.size = [[self title] sizeWithAttributes:att];
rect.origin.x = floor( NSMidX([self bounds]) - rect.size.width / 2 - 8);
rect.origin.y = floor( NSMidY([self bounds]) - rect.size.height / 2 - 5);
[fillGradient drawInBezierPath:aPath angle:90.0];
[fillGradient release];
[[self title] drawInRect:rect withAttributes:att];
[att release];
} El problema es que el NSShadow está detrás del texto no la NSBezierPath, 'Apath', ¿cómo iba a añadir la sombra del la NSBezierPath?
Solución
Trate de envolver el material de relleno NSShadow y trazado Bézier (por ejemplo, de aPath = [[NSBezierPath bezierPath] retain];
a [fillGradient release];
) en [NSGraphicsContext saveGraphicsState]
y [NSGraphicsContext restoreGraphicsState]
.
Además, la sombra puede ser cortada por los límites de la vista (que no recuerdo si esto es cierto o no).
(Además, la forma "más adecuada" para hacer esto sería probablemente a la subclase NSButtonCell
así, anulando drawWithFrame:inView:
/ -drawInteriorWithFrame:inView:
y regresar a su clase de celda personalizado del método +cellClass
de su botón (asegurándose de establecer la clase apropiada de la célula en el IB así, o intercambiar hacia fuera en -initWithCoder:
de su botón). La forma en que lo está haciendo puede satisfacer sus necesidades muy bien, sin embargo.)