【问题标题】:A UIImage created in coregraphics isn't repeating在 coregraphics 中创建的 UIImage 不会重复
【发布时间】:2012-03-19 21:03:19
【问题描述】:

我有这段代码,应该重复相同的 UIImage:

UIView *paperMiddle = [[UIView alloc] initWithFrame:CGRectMake(0, 34, 320, rect.size.height - 34)];
UIImage *paperPattern = paperBackgroundPattern(context);
paperMiddle.backgroundColor = [UIColor colorWithPatternImage:paperPattern];
[self addSubview:paperMiddle];

这是paperBackgroundPattern 方法:

UIImage *paperBackgroundPattern(CGContextRef context) {
    CGRect paper3 = CGRectMake(10, -15, 300, 16);
    CGRect paper2 = CGRectMake(13, -15, 294, 16);
    CGRect paper1 = CGRectMake(16, -15, 288, 16);

    //Shadow
    CGContextSetShadowWithColor(context, CGSizeMake(0,0), 10, [[UIColor colorWithWhite:0 alpha:0.5]CGColor]);
    CGPathRef path = createRoundedRectForRect(paper3, 0);
    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGContextAddPath(context, path);
    CGContextFillPath(context);

    //Layers of paper
    CGContextSaveGState(context);
    drawPaper(context, paper3);
    drawPaper(context, paper2);
    drawPaper(context, paper1);

    CGContextRestoreGState(context);
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(320, 1), NO, 0);
    UIImage *paperImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return paperImage;
}

它没有重复图像。有图像的结果是它显示为屏幕的顶部像素(这不是我给它的框架)。

有什么想法吗?

【问题讨论】:

标签: iphone objective-c core-graphics


【解决方案1】:

我不知道你传入的context 是什么,但不管它是什么,你都不应该画进去。而且您没有在使用 UIGraphicsBeginImageContextWithOptions 制作的上下文中绘制任何内容。

如果要生成图像,不需要传入上下文,只需使用UIGraphicsBeginImageContextWithOptions 为您制作的图像即可。

UIImage *paperBackgroundPattern() {
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(320, 1), NO, 0);
    CGContextRef context = UIGraphicsGetCurrentContext();

    // draw into context, then...

    UIImage *paperImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return paperImage;
}

另外,您真的要制作 320 pt 宽和 1 高的图像吗?您将如此精细的东西绘制到如此小的图像中,这似乎很奇怪。

【讨论】:

  • 完美,谢谢。图像有一个内部阴影,7.5 像素大。所以它需要比这更大,以使它不显示顶部或底部的阴影。我想我会删除它,因为我的代码正在更改为这种方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-17
  • 2013-03-18
  • 1970-01-01
  • 2012-05-20
  • 2014-05-25
相关资源
最近更新 更多