【问题标题】:What's the fastest way to create a transparent line in UIKit?在 UIKit 中创建透明线的最快方法是什么?
【发布时间】:2012-11-08 12:05:07
【问题描述】:

这个:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, 1)];
view.backgroundColor = [UIColor whiteColor];
view.alpha = 0.1;

或者这个:

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, 1)];
view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.1];

或者有没有第三种选择?使用带有图像的 UIImageView?使用 CoreGraphics 进行自定义绘图?什么应该是最快的?

【问题讨论】:

  • 我不知道最快,但您可能希望在测试中包含 NSBezierPath,因为这是一些 Apple 示例代码用于简单线条绘制的内容。
  • 您是否尝试过使用 CALayer?这是一个比 UIView 更轻的对象,并且使用更少的内存。我怀疑它会比 UIView 绘制得更快。
  • 你只是想画线,还是之后需要对那条线做很多操作?
  • 无操作。只需设置颜色及其 alpha/不透明度。

标签: iphone ios uikit core-graphics


【解决方案1】:

最快的方法是创建一个 CALayer。使用它可以让您在需要时轻松更改其颜色/不透明度。

CALayer *line = [CALayer new];
line.frame = CGRectMake(x, y, width, 1.0);
line.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.1].CGColor;
[someView.layer addSublayer:line];

如果你想在现有视图上画一条线并让它保持原样不动,你可以将以下代码添加到现有视图的 drawRect: 方法中:

CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, [[UIColor whiteColor] colorWithAlphaComponent:0.1].CGColor);
CGContextSetLineWidth(context, 1.0);
CGContextMoveToPoint(context, x, y);
CGContextAddLineToPoint(context, x + width, y);
CGContextStrokePath(context);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多