如何绘制不同颜色的填充路径/形状

3
我需要在屏幕上涂上我想要的任何颜色的形状。目前,我正在尝试使用UIImage来实现自己所需的颜色重绘。据我所知,唯一的方法是获取UIImage的单个像素,这需要编写比我想象中更多的代码来解决此问题。除了我已经编写的方式外,有没有其他更改UIImage颜色的方法?在上下文中绘制和填充形状会更容易吗?
谢谢。
更新:六边形正在以正确的方式绘制,但填充效果并不好。以下是代码:
self.Hexagon.lineWidth=10;
[self.Hexagon moveToPoint:CGPointMake(hexWidth/2, 0)];
[self.Hexagon addLineToPoint:CGPointMake(hexWidth, hexHeight/4)];
[self.Hexagon addLineToPoint:CGPointMake(hexWidth, hexHeight*0.75)];
[self.Hexagon addLineToPoint:CGPointMake(hexWidth/2, hexHeight)];
[self.Hexagon addLineToPoint:CGPointMake(0, hexHeight*0.75)];
[self.Hexagon addLineToPoint:CGPointMake(0, hexHeight/4)];
[self.Hexagon addLineToPoint:CGPointMake(hexWidth/2, 0)];

[self.Hexagon closePath];
[[UIColor blackColor] setStroke];
[self.Hexagon stroke];

[[UIColor whiteColor] setFill];
[self.Hexagon fill];

在程序中,使用位图(即UIImage)进行形状着色比使用CoreGraphics矢量化图像进行着色要困难得多。也许您可以告诉我们更多关于您正在制作的内容? - futureelite7
我正在尝试布置一些六边形并像我说的那样填充它们。它们是平铺的,但由于形状的特性,一些UIImageView重叠在一起。你能否链接到你提到的教程或在这里回答? - 67cherries
3个回答

4
我建议使用CAShapeLayer。你甚至可以对填充颜色进行动画处理。这样做可以保证性能良好,内存占用低。
该函数创建一个包含六边形的CGPath:(基于OP问题)
CGPathRef CGPathCreateHexagon( CGFloat hexWidth, CGFloat hexHeight )
{
    CGMutablePathRef p = CGPathCreateMutable() ;
    CGPathMoveToPoint( p, NULL,  hexWidth * 0.5, 0.0 ) ;
    CGPathAddLineToPoint( p, NULL,  hexWidth, hexHeight * 0.75 ) ;
    CGPathAddLineToPoint( p, NULL, hexWidth, hexHeight * 0.75 ) ;
    CGPathAddLineToPoint( p, NULL, hexWidth * 0.5, hexHeight ) ;
    CGPathAddLineToPoint( p, NULL, 0.0, hexHeight * 0.75 ) ;
    CGPathAddLineToPoint( p, NULL, hexWidth * 0.5, 0.0 ) ;
    CGPathAddLineToPoint( p, NULL, 0.0, hexHeight * 0.25 ) ;
    CGPathAddLineToPoint( p, NULL, hexWidth * 0.5, 0.0 ) ;
    CGPathCloseSubpath( p ) ;

    return p ;
}

设置 UIView 时使用的方法:

-(void)addHexagonLayer
{        
    CAShapeLayer * layer = [ CAShapeLayer layer ] ;
    layer.lineWidth = 10.0 ;
    {
        CGPathRef p = CGPathCreateHexagon( 100.0, 100.0 ) ;
        layer.path = p ;
        CGPathRelease( p ) ;
    }       
    layer.fillColor = [[ UIColor redColor ] CGColor ] ; // put your fill color here

    layer.position = (CGPoint){ CGRectGetMidX( self.view.bounds ), CGRectGetMidY( self.view.bounds ) } ; // position your hexagon layer appropriately.
    [ self.view.layer addSublayer:layer ] ; // add layer to your view and position appropriately        

}

编辑 我只是为了好玩创建了一个完整的演示:

#import "AppDelegate.h"

static CGPathRef CGPathCreateHexagon( CGAffineTransform * t, CGFloat w, CGFloat h )
{
    CGFloat w_4 = w * 0.25 ;
    CGFloat w_2 = w * 0.5f ;
    CGFloat h_2 = h * 0.5f ;

    CGMutablePathRef p = CGPathCreateMutable() ;
    CGPathAddLines( p, t, (CGPoint[]){
        { -w_4, h_2 }, { w_4, h_2 }, { w_2, 0 }, { w_4, -h_2 }, { -w_4, -h_2 }, { -w_2, 0 }
    }, 6 ) ;
    CGPathCloseSubpath( p ) ;

    return p ;
}

@implementation CALayer (SetPositionPixelAligned)

-(CGPoint)pixelAlignedPositionForPoint:(CGPoint)p
{
    CGSize size = self.bounds.size ;
    CGPoint anchorPoint = self.anchorPoint ;

    CGPoint result = (CGPoint){ roundf( p.x ) + anchorPoint.x * fmodf( size.width, 2.0f ), roundf( p.y ) + anchorPoint.y * fmodf( size.height, 2.0f ) } ;
    return result;
}

@end

@interface HexagonsView : UIView
@property ( nonatomic ) CGFloat hexHeight ;
@property ( nonatomic ) CGFloat hexWidth ;
@property ( nonatomic, readonly ) CGPathRef hexagonPath ;
@end

@implementation HexagonsView
@synthesize hexagonPath = _hexagonPath ;

-(void)dealloc
{
    CGPathRelease( _hexagonPath ) ;
    _hexagonPath = NULL ;
}

-(CGPathRef)hexagonPath
{
    if ( !_hexagonPath )
    {
        _hexagonPath = CGPathCreateHexagon( NULL, self.hexWidth, self.hexHeight ) ;
    }

    return _hexagonPath ;
}

-(void)setHexWidth:(CGFloat)w
{
    _hexWidth = w ;
    CGPathRelease( _hexagonPath ) ;
    _hexagonPath = NULL ;
}

-(void)setHexHeight:(CGFloat)h
{
    _hexHeight = h ;
    CGPathRelease( _hexagonPath ) ;
    _hexagonPath = NULL ;
}

-(void)layoutSubviews
{
    [ super layoutSubviews ] ;
    CGRect bounds = self.bounds ;
    bounds.size.height += self.hexHeight * 0.5 ;    // make sure we cover last row ;

    CGPoint p ;
    p.x = CGRectGetMinY( bounds ) ;

    while( p.y < CGRectGetMaxY( bounds ) )
    {
        p.x = CGRectGetMinX( bounds ) ;
        while( p.x < CGRectGetMaxX( bounds ) )
        {
            {
                CAShapeLayer * layer = [ CAShapeLayer layer ] ;
                layer.path = self.hexagonPath ;
                layer.fillColor = [[ UIColor colorWithHue:(CGFloat)arc4random_uniform( 100 ) / 256.0  saturation:1.0 brightness:1.0 alpha:1.0 ] CGColor ]  ;
                layer.position = [ layer pixelAlignedPositionForPoint:p ] ;
                [ self.layer addSublayer:layer ] ;
            }

            CGPoint p2 = { p.x + self.hexWidth * 0.75f, p.y + self.hexHeight * 0.5f } ;

            if ( p2.y < CGRectGetMaxY( bounds ))    // no unnecessary hexagons
            {
                CAShapeLayer * layer = [ CAShapeLayer layer ] ;
                layer.path = self.hexagonPath ;
                layer.fillColor = [[ UIColor colorWithHue:(CGFloat)arc4random_uniform( 256 ) / 256.0  saturation:1.0 brightness:1.0 alpha:1.0 ] CGColor ]  ;
                layer.position = [ layer pixelAlignedPositionForPoint:p2 ] ;
                [ self.layer addSublayer:layer ] ;
            }

            p.x += self.hexWidth * 1.5 ;
        }
        p.y += self.hexHeight ;
    }
}

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];

    HexagonsView * view = [[ HexagonsView alloc ] initWithFrame:self.window.bounds ] ;
    view.hexHeight = 100.0f ;
    view.hexWidth = 100.0f ;

    [ self.window addSubview:view ] ;

    [self.window makeKeyAndVisible];
    return YES;
}

@end

有默认的六边形形状吗? - 67cherries
没有内置的六边形制作函数。我修改了我的答案。 - nielsbot
为了用六边形填充您的视图,请重写-layoutSubviews并在那里创建/定位您的六边形层。 - nielsbot
你介意我使用这些代码吗?此外,你是为OSX编写的吗?我认识大部分语法,但有一些与我习惯的略有不同。也许我只是个菜鸟。 - 67cherries
当然可以使用它。它适用于iOS + ARC。您可以将UIColor替换为NSColor,将UIView替换为NSView,我认为它会起作用。 - nielsbot
哪种语法?都是Obj-C 2.0/C99(我想)。 - nielsbot

1
子类化UIView并添加以下代码:
- (void)drawRect:(CGRect)rect
{ 

        CGContextRef context = UIGraphicsGetCurrentContext(); 

//Set color of the border
        CGContextSetStrokeColorWithColor(context, [UIColor redColor].CGColor);
//Set color of the fill
        CGContextSetRGBFillColor(context, 0.0, 0.0, 1.0, 1.0);

        // Set width of border line
        CGContextSetLineWidth(context, 2.0);

//Pseudocode: Draw your hexagons with something like this
        for(int idx = 0; idx < self.points.count; idx++)
        {

            point = [self.points objectAtIndex:idx];//Edited 
            if(idx == 0)
            {
                // move to the first point
                CGContextMoveToPoint(context, point.x, point.y);
            }
            else
            {
//Add a point to the hexagon. The last point should be equal to the first point
                CGContextAddLineToPoint(context, point.x, point.y);
            }
        }
//Fill in the hexagon
        CGContextDrawPath(context, kCGPathFillStroke)
}

对于每个你想绘制的六边形,请重复此操作。理想情况下,你应该将所有六边形的点放入数组中以便轻松参考。


别忘了 "并填充" 这部分 ;) 你需要用 CGContextDrawPath(context, kCGPathFillStroke) 来代替。 - borrrden
这个实现会对性能产生很大的负面影响吗?我将绘制一百多个六边形。 - 67cherries
我不认为我会使用数组的想法,我只需要根据视图的位置来绘制它。感谢编码的建议! - 67cherries

1
创建一个UIBezierPath来描述你的形状,然后使用它的fill方法来绘制你想要的颜色。

请问您能解释一下这个怎么运作吗?我尝试了 ctx.addPath(path.cgPath); ctx.setFillColor(color.cgColor); path.fill() 但没有成功。 - Alexandru Motoc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接