可可你好世界屏保
我一直在研究NSView,因此我想我会给屏幕保护程序一个镜头。我已经能够在NSView中显示和图像,但我无法看到修改此示例代码以在ScreenSaverView中显示简单的图片。可可你好世界屏保
http://www.mactech.com/articles/mactech/Vol.20/20.06/ScreenSaversInCocoa/
BTW伟大的教程,与雪豹的工作。
我想简单地显示图像,我需要的东西,看起来像这样...
我在做什么错?
//
// try_screensaverView.m
// try screensaver
//
#import "try_screensaverView.h"
@implementation try_screensaverView
- (id)initWithFrame:(NSRect)frame isPreview:(BOOL)isPreview
{
self = [super initWithFrame:frame isPreview:isPreview];
if (self) {
[self setAnimationTimeInterval:1]; //refresh once per sec
}
return self;
}
- (void)startAnimation
{
[super startAnimation];
NSString *path = [[NSBundle mainBundle] pathForResource:@"leaf" ofType:@"JPG" inDirectory:@""];
image = [[NSImage alloc] initWithContentsOfFile:path];
}
- (void)stopAnimation
{
[super stopAnimation];
}
- (void)drawRect:(NSRect)rect
{
[super drawRect:rect];
}
- (void)animateOneFrame
{
//////////////////////////////////////////////////////////
//load image and display This does not scale the image
NSRect bounds = [self bounds];
NSSize newSize;
newSize.width = bounds.size.width;
newSize.height = bounds.size.height;
[image setSize:newSize];
NSRect imageRect;
imageRect.origin = NSZeroPoint;
imageRect.size = [image size];
NSRect drawingRect = imageRect;
[image drawInRect:drawingRect fromRect:imageRect operation:NSCompositeSourceOver fraction:1];
}
- (BOOL)hasConfigureSheet
{
return NO;
}
- (NSWindow*)configureSheet
{
return nil;
}
@end
NSRect bounds = [self bounds]; NSSize newSize; newSize.width = bounds.size.width; newSize.height = bounds.size.height; [image setSize:newSize];
我不知道你为什么这样做。
NSRect imageRect; imageRect.origin = NSZeroPoint; imageRect.size = [image size];
又名[self bounds].size
。
NSRect drawingRect = imageRect; [image drawInRect:drawingRect fromRect:imageRect operation:NSCompositeSourceOver fraction:1];
即[image drawInRect:[self bounds] fromRect:[self bounds] operation:NSCompositeSourceOver fraction:1]
。
如果您尝试以自然尺寸绘制图像,则没有理由向其发送setSize:
消息。切出整个第一部分,其余部分应该工作得很好。
如果您尝试填充屏幕(这将会缩放,会与注释相抵触),请将drawingRect
设置为[self bounds]
而不是imageRect
。这完全如此:
image,
draw into (the bounds of the view),
from (the image's entire area).
[image
drawInRect:[self bounds]
fromRect:imageRect
⋮
];
自然大小固定位置绘制和全屏绘制都不是一个有效的屏幕保护程序。后者是不可救药的;您可以通过在屏幕上对图像进行动画处理来使前者变得有用。
这很好,但它仍然不起作用。我应该在启动动画中加载图像吗? 你愿意送我一个工作的.m文件吗? 晚餐简单.m文件 在此先感谢! – 2010-03-27 05:28:50
您可能应该先载入图像;我可能会在'initWithBundle:'中执行它。如果这样做后它仍然不起作用,那么你将需要定义“不起作用”。 – 2010-03-27 08:50:48
由于您正在使用animateOneFrame
进行绘图,请尝试移除您覆盖的drawRect
。
我有类似的问题,所以我会发布我的解决方案。 OP试图通过NSBundle的mainBundle加载图像内容。相反,你会有更多的运气提取屏幕保护程序的捆绑软件并从那里加载文件,如下所示:
NSBundle *saverBundle = [NSBundle bundleForClass:[self class]];
NSImage *image = [[NSImage alloc] initWithContentsOfFile:[saverBundle pathForResource:@"image" ofType:@"png"]];
它代替什么? (顺便说一下,你正在泄漏图像,释放物体(对于非GC),并将伊娃设置为零(用于GC)来修复泄漏。) – 2010-03-17 07:24:13