在 NSView 中重复背景图像
我正在尝试在 NSView 中绘制重复的背景图像,到目前为止我已经做到了:
// INIT
- (id)initWithFrame:(NSRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundImage = [NSImage imageNamed:@"progressBackground.pdf"];
}
return self;
}
// DRAW
- (void)drawRect:(NSRect)dirtyRect {
// Draw the background
[backgroundImage drawInRect:[self bounds]
fromRect:NSMakeRect(0.0f, 0.0f, backgroundImage.size.width, backgroundImage.size.height)
operation:NSCompositeSourceAtop
fraction:1.0f];
NSLog(@"%dx%d", backgroundImage.size.width, backgroundImage.size.height);
}
但是,视图会拉伸图像以填充自身。我希望图像重复。
(黑色笔划已经修复)
此外,还发生了一些奇怪的事情,因为控制台显示图像的大小等于 -2109897792x0
,但图像实际上是 32x32
!搞什么?!
有人可以帮我吗?谢谢。
I am trying to draw a repeating background image in my NSView, I have this till now:
// INIT
- (id)initWithFrame:(NSRect)frame {
if (self = [super initWithFrame:frame]) {
self.backgroundImage = [NSImage imageNamed:@"progressBackground.pdf"];
}
return self;
}
// DRAW
- (void)drawRect:(NSRect)dirtyRect {
// Draw the background
[backgroundImage drawInRect:[self bounds]
fromRect:NSMakeRect(0.0f, 0.0f, backgroundImage.size.width, backgroundImage.size.height)
operation:NSCompositeSourceAtop
fraction:1.0f];
NSLog(@"%dx%d", backgroundImage.size.width, backgroundImage.size.height);
}
However, the view stretches the image to fill itself. I want the image to repeat instead.
(the black strokes are fixed already)
Also, something strange happens, as the console says the size of the image equals -2109897792x0
, but the image really is 32x32
! WTF?!
Could someone help me, please? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 +[NSColor colorWithPatternImage:] 然后用该“颜色”填充背景矩形。这应该可以实现您想要完成的任务。
You can create a pattern color with +[NSColor colorWithPatternImage:] and then just fill the background rectangle with that "color". That should do what you want to accomplish.
我在这里找到了答案,以防止图案从底部绘制并在窗口调整大小时产生奇怪的效果:
http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08
基本上您需要在您的drawRect 是保存你的图形上下文状态,调用该方法,绘制你的图案,然后恢复你的状态。
方法是:
我在init方法中初始化了我的背景颜色图案:
I found the answer here to prevent patterns from drawing from the bottom and giving that weird effect when windows resize:
http://www.mere-mortal-software.com/blog/details.php?d=2007-01-08
Basically all you need to do in your drawRect is to save your graphics context state, call the method, paint your pattern, then restore your state.
The method is:
I initialized my background color pattern in the init method:
在 Github 上查看
RMSkinnedView
!编辑:
RMSkinnedView
是一个NSView
子类,您可以直接通过User设置多个选项,包括圆角、背景颜色、背景图像图案等在界面生成器中定义运行时属性。Check out
RMSkinnedView
on Github!EDIT:
RMSkinnedView
is aNSView
subclass where you can set up several options, including rounded corners, background color, background image pattern, etc., directly via the User Defined Runtime Attributes in the Interface Builder.