Class: Magick::Draw

Inherits:
Object
  • Object
show all
Includes:
DrawAttribute
Defined in:
lib/rmagick_internal.rb,
ext/RMagick/rmmain.cpp

Constant Summary collapse

ALIGN_TYPE_NAMES =

These hashes are used to map Magick constant values to the strings used in the primitives.

{
  LeftAlign.to_i => 'left',
  RightAlign.to_i => 'right',
  CenterAlign.to_i => 'center'
}.freeze
ANCHOR_TYPE_NAMES =
{
  StartAnchor.to_i => 'start',
  MiddleAnchor.to_i => 'middle',
  EndAnchor.to_i => 'end'
}.freeze
DECORATION_TYPE_NAMES =
{
  NoDecoration.to_i => 'none',
  UnderlineDecoration.to_i => 'underline',
  OverlineDecoration.to_i => 'overline',
  LineThroughDecoration.to_i => 'line-through'
}.freeze
FONT_WEIGHT_NAMES =
{
  AnyWeight.to_i => 'all',
  NormalWeight.to_i => 'normal',
  BoldWeight.to_i => 'bold',
  BolderWeight.to_i => 'bolder',
  LighterWeight.to_i => 'lighter'
}.freeze
GRAVITY_NAMES =
{
  NorthWestGravity.to_i => 'northwest',
  NorthGravity.to_i => 'north',
  NorthEastGravity.to_i => 'northeast',
  WestGravity.to_i => 'west',
  CenterGravity.to_i => 'center',
  EastGravity.to_i => 'east',
  SouthWestGravity.to_i => 'southwest',
  SouthGravity.to_i => 'south',
  SouthEastGravity.to_i => 'southeast'
}.freeze
PAINT_METHOD_NAMES =
{
  PointMethod.to_i => 'point',
  ReplaceMethod.to_i => 'replace',
  FloodfillMethod.to_i => 'floodfill',
  FillToBorderMethod.to_i => 'filltoborder',
  ResetMethod.to_i => 'reset'
}.freeze
STRETCH_TYPE_NAMES =
{
  NormalStretch.to_i => 'normal',
  UltraCondensedStretch.to_i => 'ultra-condensed',
  ExtraCondensedStretch.to_i => 'extra-condensed',
  CondensedStretch.to_i => 'condensed',
  SemiCondensedStretch.to_i => 'semi-condensed',
  SemiExpandedStretch.to_i => 'semi-expanded',
  ExpandedStretch.to_i => 'expanded',
  ExtraExpandedStretch.to_i => 'extra-expanded',
  UltraExpandedStretch.to_i => 'ultra-expanded',
  AnyStretch.to_i => 'all'
}.freeze
STYLE_TYPE_NAMES =
{
  NormalStyle.to_i => 'normal',
  ItalicStyle.to_i => 'italic',
  ObliqueStyle.to_i => 'oblique',
  AnyStyle.to_i => 'all'
}.freeze

Instance Method Summary collapse

Methods included from DrawAttribute

#affine=, #align=, #decorate=, #density=, #encoding=, #fill=, #fill_pattern=, #font=, #font_family=, #font_stretch=, #font_style=, #font_weight=, #gravity=, #interline_spacing=, #interword_spacing=, #kerning=, #pointsize=, #rotation=, #stroke=, #stroke_pattern=, #stroke_width=, #text_antialias=, #tile=, #undercolor=

Constructor Details

#initializeMagick::Draw

Initialize Draw object.



1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
# File 'ext/RMagick/rmdraw.cpp', line 1284

VALUE
Draw_initialize(VALUE self)
{
    Draw *draw, *draw_options;
    VALUE options;

    TypedData_Get_Struct(self, Draw, &rm_draw_data_type, draw);

    options = new_DrawOptions();
    TypedData_Get_Struct(options, Draw, &rm_draw_data_type, draw_options);
    draw->info = draw_options->info;
    draw_options->info = NULL;

    RB_GC_GUARD(options);

    return self;
}

Instance Method Details

#affine(sx, rx, ry, sy, tx, ty) ⇒ Object

Apply coordinate transformations to support scaling (s), rotation (r), and translation (t). Angles are specified in radians.



256
257
258
# File 'lib/rmagick_internal.rb', line 256

def affine(sx, rx, ry, sy, tx, ty)
  primitive 'affine ' + sprintf('%g,%g,%g,%g,%g,%g', sx, rx, ry, sy, tx, ty)
end

#alpha(x, y, method) ⇒ Object

Set alpha (make transparent) in image according to the specified colorization rule



262
263
264
265
266
# File 'lib/rmagick_internal.rb', line 262

def alpha(x, y, method)
  Kernel.raise ArgumentError, 'Unknown paint method' unless PAINT_METHOD_NAMES.key?(method.to_i)
  name = Gem::Version.new(Magick::IMAGEMAGICK_VERSION) > Gem::Version.new('7.0.0') ? 'alpha ' : 'matte '
  primitive name + sprintf('%g,%g, %s', x, y, PAINT_METHOD_NAMES[method.to_i])
end

#annotate(image_arg, width_arg, height_arg, x_arg, y_arg, text) ⇒ Magick::Draw

Annotates an image with text.

  • Additional Draw attribute methods may be called in the optional block, which is executed in the context of a Draw object.

Parameters:

  • image_arg (Magick::Image, Magick::ImageList)

    Either an imagelist or an image. If an imagelist, uses the current image.

  • width_arg (Numeric)

    the width

  • height_arg (Numeric)

    the height

  • x_arg (Numeric)

    x position

  • y_arg (Numeric)

    y position

  • text (String)

    the annotation text

Returns:



980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
# File 'ext/RMagick/rmdraw.cpp', line 980

VALUE Draw_annotate(
                   VALUE self,
                   VALUE image_arg,
                   VALUE width_arg,
                   VALUE height_arg,
                   VALUE x_arg,
                   VALUE y_arg,
                   VALUE text)
{
    struct Draw_annotate_args annotate;

    // Save the affine matrix in case it is modified by
    // Draw#rotation=
    annotate.draw = get_draw(self);
    annotate.keep = annotate.draw->info->affine;

    annotate.self       = self;
    annotate.image_arg  = rm_cur_image(image_arg);
    annotate.width_arg  = width_arg;
    annotate.height_arg = height_arg;
    annotate.x_arg      = x_arg;
    annotate.y_arg      = y_arg;
    annotate.text       = text;
#if defined(IMAGEMAGICK_7)
    annotate.exception  = NULL;
#endif

    rm_check_frozen(annotate.image_arg);

    return rb_ensure(annotate_body, (VALUE)&annotate, annotate_ensure, (VALUE)&annotate);
}

#arc(start_x, start_y, end_x, end_y, start_degrees, end_degrees) ⇒ Object

Draw an arc.



269
270
271
272
273
274
# File 'lib/rmagick_internal.rb', line 269

def arc(start_x, start_y, end_x, end_y, start_degrees, end_degrees)
  primitive 'arc ' + sprintf(
    '%g,%g %g,%g %g,%g',
    start_x, start_y, end_x, end_y, start_degrees, end_degrees
  )
end

#bezier(*points) ⇒ Object

Draw a bezier curve.



277
278
279
280
281
282
283
284
# File 'lib/rmagick_internal.rb', line 277

def bezier(*points)
  if points.empty?
    Kernel.raise ArgumentError, 'no points specified'
  elsif points.length.odd?
    Kernel.raise ArgumentError, 'odd number of arguments specified'
  end
  primitive 'bezier ' + points.map! { |x| sprintf('%g', x) }.join(',')
end

#circle(origin_x, origin_y, perim_x, perim_y) ⇒ Object

Draw a circle



287
288
289
# File 'lib/rmagick_internal.rb', line 287

def circle(origin_x, origin_y, perim_x, perim_y)
  primitive 'circle ' + sprintf('%g,%g %g,%g', origin_x, origin_y, perim_x, perim_y)
end

#clip_path(name) ⇒ Object

Invoke a clip-path defined by def_clip_path.



292
293
294
# File 'lib/rmagick_internal.rb', line 292

def clip_path(name)
  primitive "clip-path #{enquote(name)}"
end

#clip_rule(rule) ⇒ Object

Define the clipping rule.



297
298
299
300
301
# File 'lib/rmagick_internal.rb', line 297

def clip_rule(rule)
  rule = to_string(rule)
  Kernel.raise ArgumentError, "Unknown clipping rule #{rule}" unless %w[evenodd nonzero].include?(rule.downcase)
  primitive "clip-rule #{rule}"
end

#clip_units(unit) ⇒ Object

Define the clip units



304
305
306
307
308
# File 'lib/rmagick_internal.rb', line 304

def clip_units(unit)
  unit = to_string(unit)
  Kernel.raise ArgumentError, "Unknown clip unit #{unit}" unless %w[userspace userspaceonuse objectboundingbox].include?(unit.downcase)
  primitive "clip-units #{unit}"
end

#cloneMagick::Draw

Clones this object.

Returns:



1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'ext/RMagick/rmdraw.cpp', line 1018

VALUE
Draw_clone(VALUE self)
{
    VALUE clone;

    clone = Draw_dup(self);
    if (OBJ_FROZEN(self))
    {
        OBJ_FREEZE(clone);
    }

    RB_GC_GUARD(clone);

    return clone;
}

#color(x, y, method) ⇒ Object

Set color in image according to specified colorization rule. Rule is one of point, replace, floodfill, filltoborder,reset



312
313
314
315
# File 'lib/rmagick_internal.rb', line 312

def color(x, y, method)
  Kernel.raise ArgumentError, "Unknown PaintMethod: #{method}" unless PAINT_METHOD_NAMES.key?(method.to_i)
  primitive 'color ' + sprintf('%g,%g,%s', x, y, PAINT_METHOD_NAMES[method.to_i])
end

#composite(x, y, width, height, image) ⇒ Magick::Draw #composite(x, y, width, height, image, composite_op = Magick::OverCompositeOp) ⇒ Magick::Draw

Draw the image.

Overloads:

  • #composite(x, y, width, height, image) ⇒ Magick::Draw

    Parameters:

    • x (Numeric)

      x position

    • y (Numeric)

      y position

    • width (Numeric)

      the width

    • height (Numeric)

      the height

    • image (Magick::Image, Magick::ImageList)

      Either an imagelist or an image. If an imagelist, uses the current image.

  • #composite(x, y, width, height, image, composite_op = Magick::OverCompositeOp) ⇒ Magick::Draw
    • The "image" argument can be either an ImageList object or an Image argument.

    Parameters:

    • x (Numeric)

      x position

    • y (Numeric)

      y position

    • width (Numeric)

      the width

    • height (Numeric)

      the height

    • image (Magick::Image, Magick::ImageList)

      Either an imagelist or an image. If an imagelist, uses the current image.

    • composite_op (Magick::CompositeOperator) (defaults to: Magick::OverCompositeOp)

      the operator

Returns:



1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
# File 'ext/RMagick/rmdraw.cpp', line 1059

VALUE
Draw_composite(int argc, VALUE *argv, VALUE self)
{
    Draw *draw;
    const char *op;
    double x, y, width, height;
    CompositeOperator composite_op;
    VALUE image;
    Image *comp_img;
    struct TmpFile_Name *tmpfile_name;
    char name[MaxTextExtent];
    // Buffer for "image" primitive
    char primitive[MaxTextExtent];

    if (argc < 5 || argc > 6)
    {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 5 or 6)", argc);
    }

    // Retrieve the image to composite
    image = rm_cur_image(argv[4]);
    comp_img = rm_check_destroyed(image);

    x = NUM2DBL(argv[0]);
    y = NUM2DBL(argv[1]);
    width  = NUM2DBL(argv[2]);
    height = NUM2DBL(argv[3]);

    composite_op = OverCompositeOp;
    if (argc == 6)
    {
        VALUE_TO_ENUM(argv[5], composite_op, CompositeOperator);
    }

    op = CommandOptionToMnemonic(MagickComposeOptions, composite_op);
    if (rm_strcasecmp("Unrecognized", op) == 0)
    {
        rb_raise(rb_eArgError, "unknown composite operator (%d)", composite_op);
    }

    TypedData_Get_Struct(self, Draw, &rm_draw_data_type, draw);

    // Create a temp copy of the composite image
    rm_write_temp_image(comp_img, name, sizeof(name));

    // Add the temp filename to the filename array.
    // Use Magick storage since we need to keep the list around
    // until destroy_Draw is called.
    tmpfile_name = (struct TmpFile_Name *)magick_malloc(sizeof(struct TmpFile_Name) + rm_strnlen_s(name, sizeof(name)));
    strcpy(tmpfile_name->name, name);
    tmpfile_name->next = draw->tmpfile_ary;
    draw->tmpfile_ary = tmpfile_name;

    // Form the drawing primitive
    snprintf(primitive, sizeof(primitive), "image %s %g,%g,%g,%g '%s'", op, x, y, width, height, name);


    // Send "primitive" to self.
    rb_funcall(self, rb_intern("primitive"), 1, rb_str_new2(primitive));

    RB_GC_GUARD(image);

    return self;
}

#decorate(decoration) ⇒ Object

Specify EITHER the text decoration (none, underline, overline, line-through) OR the text solid background color (any color name or spec)



319
320
321
322
323
324
325
# File 'lib/rmagick_internal.rb', line 319

def decorate(decoration)
  if DECORATION_TYPE_NAMES.key?(decoration.to_i)
    primitive "decorate #{DECORATION_TYPE_NAMES[decoration.to_i]}"
  else
    primitive "decorate #{enquote(decoration)}"
  end
end

#define_clip_path(name) ⇒ Object

Define a clip-path. A clip-path is a sequence of primitives bracketed by the "push clip-path " and "pop clip-path" primitives. Upon advice from the IM guys, we also bracket the clip-path primitives with "push(pop) defs" and "push (pop) graphic-context".



332
333
334
335
336
337
338
339
340
341
# File 'lib/rmagick_internal.rb', line 332

def define_clip_path(name)
  push('defs')
  push("clip-path #{enquote(name)}")
  push('graphic-context')
  yield
ensure
  pop('graphic-context')
  pop('clip-path')
  pop('defs')
end

#draw(image_arg) ⇒ Magick::Draw

Execute the stored drawing primitives on the current image.

Parameters:

Returns:



1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
# File 'ext/RMagick/rmdraw.cpp', line 1132

VALUE
Draw_draw(VALUE self, VALUE image_arg)
{
    Draw *draw;
    Image *image;
#if defined(IMAGEMAGICK_7)
    ExceptionInfo *exception;
#endif

    image_arg = rm_cur_image(image_arg);
    image = rm_check_frozen(image_arg);

    draw = get_draw(self);
    if (draw->primitives == 0)
    {
        rb_raise(rb_eArgError, "nothing to draw");
    }

    // Point the DrawInfo structure at the current set of primitives.
    magick_clone_string(&(draw->info->primitive), StringValueCStr(draw->primitives));

#if defined(IMAGEMAGICK_7)
    exception = AcquireExceptionInfo();
    GVL_STRUCT_TYPE(DrawImage) args = { image, draw->info, exception };
#else
    GVL_STRUCT_TYPE(DrawImage) args = { image, draw->info };
#endif
    CALL_FUNC_WITHOUT_GVL(GVL_FUNC(DrawImage), &args);

    magick_free(draw->info->primitive);
    draw->info->primitive = NULL;

#if defined(IMAGEMAGICK_7)
    CHECK_EXCEPTION();
    DestroyExceptionInfo(exception);
#else
    rm_check_image_exception(image, RetainOnError);
#endif

    return self;
}

#dupMagick::Draw

Duplicate a Draw object.

  • Constructs a new Draw object, then calls initialize_copy.

Returns:



1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
# File 'ext/RMagick/rmdraw.cpp', line 1182

VALUE
Draw_dup(VALUE self)
{
    Draw *draw;
    VALUE dup;

    draw = ALLOC(Draw);
    memset(draw, 0, sizeof(Draw));
    dup = TypedData_Wrap_Struct(CLASS_OF(self), &rm_draw_data_type, draw);
    RB_GC_GUARD(dup);

    return rb_funcall(dup, rm_ID_initialize_copy, 1, self);
}

#ellipse(origin_x, origin_y, width, height, arc_start, arc_end) ⇒ Object

Draw an ellipse



344
345
346
347
348
349
# File 'lib/rmagick_internal.rb', line 344

def ellipse(origin_x, origin_y, width, height, arc_start, arc_end)
  primitive 'ellipse ' + sprintf(
    '%g,%g %g,%g %g,%g',
    origin_x, origin_y, width, height, arc_start, arc_end
  )
end

#encoding(encoding) ⇒ Object

Let anything through, but the only defined argument is "UTF-8". All others are apparently ignored.



353
354
355
# File 'lib/rmagick_internal.rb', line 353

def encoding(encoding)
  primitive "encoding #{enquote(encoding)}"
end

#fill(colorspec) ⇒ Object Also known as: fill_color, fill_pattern

Specify object fill, a color name or pattern name



358
359
360
# File 'lib/rmagick_internal.rb', line 358

def fill(colorspec)
  primitive "fill #{enquote(colorspec)}"
end

#fill_opacity(opacity) ⇒ Object

Specify fill opacity (use "xx%" to indicate percentage)



365
366
367
368
# File 'lib/rmagick_internal.rb', line 365

def fill_opacity(opacity)
  opacity = to_opacity(opacity)
  primitive "fill-opacity #{opacity}"
end

#fill_rule(rule) ⇒ Object



370
371
372
373
374
# File 'lib/rmagick_internal.rb', line 370

def fill_rule(rule)
  rule = to_string(rule)
  Kernel.raise ArgumentError, "Unknown fill rule #{rule}" unless %w[evenodd nonzero].include?(rule.downcase)
  primitive "fill-rule #{rule}"
end

#font(name) ⇒ Object

Specify text drawing font



377
378
379
# File 'lib/rmagick_internal.rb', line 377

def font(name)
  primitive "font #{enquote(name)}"
end

#font_family(name) ⇒ Object



381
382
383
# File 'lib/rmagick_internal.rb', line 381

def font_family(name)
  primitive "font-family #{enquote(name)}"
end

#font_stretch(stretch) ⇒ Object



385
386
387
388
# File 'lib/rmagick_internal.rb', line 385

def font_stretch(stretch)
  Kernel.raise ArgumentError, 'Unknown stretch type' unless STRETCH_TYPE_NAMES.key?(stretch.to_i)
  primitive "font-stretch #{STRETCH_TYPE_NAMES[stretch.to_i]}"
end

#font_style(style) ⇒ Object



390
391
392
393
# File 'lib/rmagick_internal.rb', line 390

def font_style(style)
  Kernel.raise ArgumentError, 'Unknown style type' unless STYLE_TYPE_NAMES.key?(style.to_i)
  primitive "font-style #{STYLE_TYPE_NAMES[style.to_i]}"
end

#font_weight(weight) ⇒ Object

The font weight argument can be either a font weight constant or [100,200,...,900]



397
398
399
400
401
402
403
# File 'lib/rmagick_internal.rb', line 397

def font_weight(weight)
  if weight.is_a?(WeightType)
    primitive "font-weight #{FONT_WEIGHT_NAMES[weight.to_i]}"
  else
    primitive "font-weight #{Integer(weight)}"
  end
end

#get_multiline_type_metrics(text) ⇒ Magick::TypeMetric #DrawMagick::TypeMetric

Returns measurements for a given font and text string.

  • If the image argument has been omitted, use a dummy image, but make sure the text has none of the special characters that refer to image attributes.

Overloads:

  • #get_multiline_type_metrics(text) ⇒ Magick::TypeMetric

    Parameters:

    • text (String)

      The string to be rendered.

  • #DrawMagick::TypeMetric

    Parameters:

    • image (Magick::Image, Magick::ImageList)

      Either an imagelist or an image. If an imagelist, uses the current image.

    • text (String)

      The string to be rendered.

Returns:

  • (Magick::TypeMetric)

    The information for a specific string if rendered on an image.



1241
1242
1243
1244
1245
1246
1247
1248
# File 'ext/RMagick/rmdraw.cpp', line 1241

VALUE
Draw_get_multiline_type_metrics(
                               int argc,
                               VALUE *argv,
                               VALUE self)
{
    return get_type_metrics(argc, argv, self, GVL_FUNC(GetMultilineTypeMetrics));
}

#get_type_metrics(text) ⇒ Magick::TypeMetric #get_type_metrics(image, text) ⇒ Magick::TypeMetric

Returns measurements for a given font and text string.

  • If the image argument has been omitted, use a dummy image, but make sure the text has none of the special characters that refer to image attributes.

Overloads:

  • #get_type_metrics(text) ⇒ Magick::TypeMetric

    Parameters:

    • text (String)

      The string to be rendered.

  • #get_type_metrics(image, text) ⇒ Magick::TypeMetric

    Parameters:

    • image (Magick::Image, Magick::ImageList)

      Either an imagelist or an image. If an imagelist, uses the current image.

    • text (String)

      The string to be rendered.

Returns:

  • (Magick::TypeMetric)

    The information for a specific string if rendered on an image.



1214
1215
1216
1217
1218
1219
1220
1221
# File 'ext/RMagick/rmdraw.cpp', line 1214

VALUE
Draw_get_type_metrics(
                     int argc,
                     VALUE *argv,
                     VALUE self)
{
    return get_type_metrics(argc, argv, self, GVL_FUNC(GetTypeMetrics));
}

#gravity(grav) ⇒ Object

Specify the text positioning gravity, one of: NorthWest, North, NorthEast, West, Center, East, SouthWest, South, SouthEast



407
408
409
410
# File 'lib/rmagick_internal.rb', line 407

def gravity(grav)
  Kernel.raise ArgumentError, 'Unknown text positioning gravity' unless GRAVITY_NAMES.key?(grav.to_i)
  primitive "gravity #{GRAVITY_NAMES[grav.to_i]}"
end

#image(composite, x, y, width, height, image_file_path) ⇒ Object



412
413
414
415
416
# File 'lib/rmagick_internal.rb', line 412

def image(composite, x, y, width, height, image_file_path)
  Kernel.raise ArgumentError, 'Unknown composite' unless composite.is_a?(CompositeOperator)
  composite_name = composite.to_s.sub!('CompositeOp', '')
  primitive 'image ' + sprintf('%s %g,%g %g,%g %s', composite_name, x, y, width, height, enquote(image_file_path))
end

#initialize_copy(orig) ⇒ Magick::Draw

Initialize clone, dup methods.

Parameters:

  • orig

    the original object

Returns:



1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
# File 'ext/RMagick/rmdraw.cpp', line 1257

VALUE Draw_init_copy(VALUE self, VALUE orig)
{
    Draw *copy, *original;

    TypedData_Get_Struct(orig, Draw, &rm_draw_data_type, original);
    TypedData_Get_Struct(self, Draw, &rm_draw_data_type, copy);

    copy->info = CloneDrawInfo(NULL, original->info);
    if (!copy->info)
    {
        rb_raise(rb_eNoMemError, "not enough memory to continue");
    }

    if (original->primitives)
    {
        copy->primitives = rb_str_dup(original->primitives);
    }

    return self;
}

#inspectString

Display the primitives.

Returns:

  • (String)

    the draw primitives or the Ruby string "(no primitives defined)" if they are not defined



1309
1310
1311
1312
1313
1314
1315
1316
# File 'ext/RMagick/rmdraw.cpp', line 1309

VALUE
Draw_inspect(VALUE self)
{
    Draw *draw;

    TypedData_Get_Struct(self, Draw, &rm_draw_data_type, draw);
    return draw->primitives ? draw->primitives : rb_str_new2("(no primitives defined)");
}

#interline_spacing(space) ⇒ Object

IM 6.5.5-8 and later



419
420
421
# File 'lib/rmagick_internal.rb', line 419

def interline_spacing(space)
  primitive "interline-spacing #{Float(space)}"
end

#interword_spacing(space) ⇒ Object

IM 6.4.8-3 and later



424
425
426
# File 'lib/rmagick_internal.rb', line 424

def interword_spacing(space)
  primitive "interword-spacing #{Float(space)}"
end

#kerning(space) ⇒ Object

IM 6.4.8-3 and later



429
430
431
# File 'lib/rmagick_internal.rb', line 429

def kerning(space)
  primitive "kerning #{Float(space)}"
end

#line(start_x, start_y, end_x, end_y) ⇒ Object

Draw a line



434
435
436
# File 'lib/rmagick_internal.rb', line 434

def line(start_x, start_y, end_x, end_y)
  primitive 'line ' + sprintf('%g,%g %g,%g', start_x, start_y, end_x, end_y)
end

#marshal_dumpHash

TODO:

Handle gradients when christy gets the new gradient support added (23Dec08)

Dump custom marshal for Draw objects.

  • Instead of trying to replicate Ruby's support for cross-system marshalling, exploit it. Convert the Draw fields to Ruby objects and store them in a hash. Let Ruby marshal the hash.
  • Commented out code that dumps/loads fields that are used internally by ImageMagick and shouldn't be marshaled. I left the code as placeholders so I'll know which fields have been deliberately omitted.

Returns:

  • (Hash)

    the marshalled object



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'ext/RMagick/rmdraw.cpp', line 533

VALUE
Draw_marshal_dump(VALUE self)
{
    Draw *draw;
    VALUE ddraw;

    draw = get_draw(self);

    // Raise an exception if the Draw has a non-NULL gradient or element_reference field
    if (draw->info->element_reference.type != UndefinedReference
        || draw->info->gradient.type != UndefinedGradient)
    {
        rb_raise(rb_eTypeError, "can't dump gradient definition");
    }

    ddraw = rb_hash_new();

    rb_hash_aset(ddraw, CSTR2SYM("affine"), Import_AffineMatrix(&draw->info->affine));
    rb_hash_aset(ddraw, CSTR2SYM("gravity"), INT2FIX(draw->info->gravity));
    rb_hash_aset(ddraw, CSTR2SYM("fill"), Pixel_from_PixelColor(&draw->info->fill));
    rb_hash_aset(ddraw, CSTR2SYM("stroke"), Pixel_from_PixelColor(&draw->info->stroke));
    rb_hash_aset(ddraw, CSTR2SYM("stroke_width"), rb_float_new(draw->info->stroke_width));
    rb_hash_aset(ddraw, CSTR2SYM("fill_pattern"), image_to_str(draw->info->fill_pattern));
    rb_hash_aset(ddraw, CSTR2SYM("stroke_pattern"), image_to_str(draw->info->stroke_pattern));
    rb_hash_aset(ddraw, CSTR2SYM("stroke_antialias"), draw->info->stroke_antialias ? Qtrue : Qfalse);
    rb_hash_aset(ddraw, CSTR2SYM("text_antialias"), draw->info->text_antialias ? Qtrue : Qfalse);
    rb_hash_aset(ddraw, CSTR2SYM("decorate"), INT2FIX(draw->info->decorate));
    rb_hash_aset(ddraw, CSTR2SYM("font"), MAGICK_STRING_TO_OBJ(draw->info->font));
    rb_hash_aset(ddraw, CSTR2SYM("family"), MAGICK_STRING_TO_OBJ(draw->info->family));
    rb_hash_aset(ddraw, CSTR2SYM("style"), INT2FIX(draw->info->style));
    rb_hash_aset(ddraw, CSTR2SYM("stretch"), INT2FIX(draw->info->stretch));
    rb_hash_aset(ddraw, CSTR2SYM("weight"), ULONG2NUM(draw->info->weight));
    rb_hash_aset(ddraw, CSTR2SYM("encoding"), MAGICK_STRING_TO_OBJ(draw->info->encoding));
    rb_hash_aset(ddraw, CSTR2SYM("pointsize"), rb_float_new(draw->info->pointsize));
    rb_hash_aset(ddraw, CSTR2SYM("density"), MAGICK_STRING_TO_OBJ(draw->info->density));
    rb_hash_aset(ddraw, CSTR2SYM("align"), INT2FIX(draw->info->align));
    rb_hash_aset(ddraw, CSTR2SYM("undercolor"), Pixel_from_PixelColor(&draw->info->undercolor));
    rb_hash_aset(ddraw, CSTR2SYM("clip_units"), INT2FIX(draw->info->clip_units));
#if defined(IMAGEMAGICK_7)
    rb_hash_aset(ddraw, CSTR2SYM("alpha"), QUANTUM2NUM(draw->info->alpha));
#else
    rb_hash_aset(ddraw, CSTR2SYM("opacity"), QUANTUM2NUM(draw->info->opacity));
#endif
    rb_hash_aset(ddraw, CSTR2SYM("kerning"), rb_float_new(draw->info->kerning));
    rb_hash_aset(ddraw, CSTR2SYM("interword_spacing"), rb_float_new(draw->info->interword_spacing));

    // Non-DrawInfo fields
    rb_hash_aset(ddraw, CSTR2SYM("primitives"), draw->primitives);

    return ddraw;
}

#marshal_load(ddraw) ⇒ Magick::Draw

Load the marshalled object

Parameters:

  • ddraw (Hash)

    the marshalled object

Returns:



592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
# File 'ext/RMagick/rmdraw.cpp', line 592

VALUE
Draw_marshal_load(VALUE self, VALUE ddraw)
{
    Draw *draw;
    VALUE val;

    TypedData_Get_Struct(self, Draw, &rm_draw_data_type, draw);

    Check_Type(ddraw, T_HASH);

    if (draw->info == NULL)
    {
        ImageInfo *image_info;

        image_info = CloneImageInfo(NULL);
        draw->info = CloneDrawInfo(image_info, (DrawInfo *) NULL);
        DestroyImageInfo(image_info);
    }
    OBJ_TO_MAGICK_STRING(draw->info->geometry, rb_hash_aref(ddraw, CSTR2SYM("geometry")));

    val = rb_hash_aref(ddraw, CSTR2SYM("affine"));
    Export_AffineMatrix(&draw->info->affine, val);

    draw->info->gravity = (GravityType) FIX2INT(rb_hash_aref(ddraw, CSTR2SYM("gravity")));

    val = rb_hash_aref(ddraw, CSTR2SYM("fill"));
    Color_to_PixelColor(&draw->info->fill, val);

    val = rb_hash_aref(ddraw, CSTR2SYM("stroke"));
    Color_to_PixelColor(&draw->info->stroke, val);

    draw->info->stroke_width = NUM2DBL(rb_hash_aref(ddraw, CSTR2SYM("stroke_width")));
    draw->info->fill_pattern = str_to_image(rb_hash_aref(ddraw, CSTR2SYM("fill_pattern")));
    draw->info->stroke_pattern = str_to_image(rb_hash_aref(ddraw, CSTR2SYM("stroke_pattern")));
    draw->info->stroke_antialias = (MagickBooleanType)RTEST(rb_hash_aref(ddraw, CSTR2SYM("stroke_antialias")));
    draw->info->text_antialias = (MagickBooleanType)RTEST(rb_hash_aref(ddraw, CSTR2SYM("text_antialias")));
    draw->info->decorate = (DecorationType) FIX2INT(rb_hash_aref(ddraw, CSTR2SYM("decorate")));
    OBJ_TO_MAGICK_STRING(draw->info->font, rb_hash_aref(ddraw, CSTR2SYM("font")));
    OBJ_TO_MAGICK_STRING(draw->info->family, rb_hash_aref(ddraw, CSTR2SYM("family")));

    draw->info->style = (StyleType) FIX2INT(rb_hash_aref(ddraw, CSTR2SYM("style")));
    draw->info->stretch = (StretchType) FIX2INT(rb_hash_aref(ddraw, CSTR2SYM("stretch")));
    draw->info->weight = NUM2ULONG(rb_hash_aref(ddraw, CSTR2SYM("weight")));
    OBJ_TO_MAGICK_STRING(draw->info->encoding, rb_hash_aref(ddraw, CSTR2SYM("encoding")));
    draw->info->pointsize = NUM2DBL(rb_hash_aref(ddraw, CSTR2SYM("pointsize")));
    OBJ_TO_MAGICK_STRING(draw->info->density, rb_hash_aref(ddraw, CSTR2SYM("density")));
    draw->info->align = (AlignType) FIX2INT(rb_hash_aref(ddraw, CSTR2SYM("align")));

    val = rb_hash_aref(ddraw, CSTR2SYM("undercolor"));
    Color_to_PixelColor(&draw->info->undercolor, val);

    draw->info->clip_units = (ClipPathUnits)FIX2INT(rb_hash_aref(ddraw, CSTR2SYM("clip_units")));
#if defined(IMAGEMAGICK_7)
    draw->info->alpha = NUM2QUANTUM(rb_hash_aref(ddraw, CSTR2SYM("alpha")));
#else
    draw->info->opacity = NUM2QUANTUM(rb_hash_aref(ddraw, CSTR2SYM("opacity")));
#endif
    draw->info->kerning = NUM2DBL(rb_hash_aref(ddraw, CSTR2SYM("kerning")));
    draw->info->interword_spacing = NUM2DBL(rb_hash_aref(ddraw, CSTR2SYM("interword_spacing")));

    draw->primitives = rb_hash_aref(ddraw, CSTR2SYM("primitives"));

    RB_GC_GUARD(val);

    return self;
}

#opacity(opacity) ⇒ Object

Specify drawing fill and stroke opacities. If the value is a string ending with a %, the number will be multiplied by 0.01.



440
441
442
443
# File 'lib/rmagick_internal.rb', line 440

def opacity(opacity)
  opacity = to_opacity(opacity)
  primitive "opacity #{opacity}"
end

#path(cmds) ⇒ Object

Draw using SVG-compatible path drawing commands. Note that the primitive requires that the commands be surrounded by quotes or apostrophes. Here we simply use apostrophes.



448
449
450
# File 'lib/rmagick_internal.rb', line 448

def path(cmds)
  primitive "path #{enquote(cmds)}"
end

#pattern(name, x, y, width, height) ⇒ Object

Define a pattern. In the block, call primitive methods to draw the pattern. Reference the pattern by using its name as the argument to the 'fill' or 'stroke' methods



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# File 'lib/rmagick_internal.rb', line 455

def pattern(name, x, y, width, height)
  name = to_string(name)
  Kernel.raise ArgumentError, 'pattern name must consist of letters, digits, hyphen, period and underscore' unless /\A[\w.-]+\z/.match?(name)

  viewport = sprintf('%g %g %g %g', x, y, width, height)

  push('defs')
  push("pattern #{name} " + viewport)
  push('graphic-context')
  begin
    yield
  ensure
    pop('graphic-context')
    pop('pattern')
    pop('defs')
  end
end

#point(x, y) ⇒ Object

Set point to fill color.



474
475
476
# File 'lib/rmagick_internal.rb', line 474

def point(x, y)
  primitive 'point ' + sprintf('%g,%g', x, y)
end

#pointsize(points) ⇒ Object Also known as: font_size

Specify the font size in points. Yes, the primitive is "font-size" but in other places this value is called the "pointsize". Give it both names.



480
481
482
# File 'lib/rmagick_internal.rb', line 480

def pointsize(points)
  primitive 'font-size ' + sprintf('%g', points)
end

#polygon(*points) ⇒ Object

Draw a polygon



486
487
488
489
490
491
492
493
# File 'lib/rmagick_internal.rb', line 486

def polygon(*points)
  if points.empty?
    Kernel.raise ArgumentError, 'no points specified'
  elsif points.length.odd?
    Kernel.raise ArgumentError, 'odd number of points specified'
  end
  primitive 'polygon ' + points.map! { |x| sprintf('%g', x) }.join(',')
end

#polyline(*points) ⇒ Object

Draw a polyline



496
497
498
499
500
501
502
503
# File 'lib/rmagick_internal.rb', line 496

def polyline(*points)
  if points.empty?
    Kernel.raise ArgumentError, 'no points specified'
  elsif points.length.odd?
    Kernel.raise ArgumentError, 'odd number of points specified'
  end
  primitive 'polyline ' + points.map! { |x| sprintf('%g', x) }.join(',')
end

#pop(*what) ⇒ Object

Return to the previously-saved set of whatever pop('graphic-context') (the default if no arguments) pop('defs') pop('gradient') pop('pattern')



511
512
513
514
515
516
517
# File 'lib/rmagick_internal.rb', line 511

def pop(*what)
  if what.empty?
    primitive 'pop graphic-context'
  else
    primitive 'pop ' + what.map { |x| to_string(x) }.join(' ')
  end
end

#primitive(primitive) ⇒ Magick::Draw

Add a drawing primitive to the list of primitives in the Draw object.

Parameters:

  • primitive (String)

    the primitive to add

Returns:



1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
# File 'ext/RMagick/rmdraw.cpp', line 1345

VALUE
Draw_primitive(VALUE self, VALUE primitive)
{
    Draw *draw;

    rb_check_frozen(self);
    StringValue(primitive);
    TypedData_Get_Struct(self, Draw, &rm_draw_data_type, draw);

    if (draw->primitives == (VALUE)0)
    {
        draw->primitives = rb_str_dup(primitive);
    }
    else
    {
        draw->primitives = rb_str_concat(draw->primitives, rb_str_new2("\n"));
        draw->primitives = rb_str_concat(draw->primitives, primitive);
    }

    return self;
}

#push(*what) ⇒ Object

Push the current set of drawing options. Also you can use push('graphic-context') (the default if no arguments) push('defs') push('gradient') push('pattern')



524
525
526
527
528
529
530
# File 'lib/rmagick_internal.rb', line 524

def push(*what)
  if what.empty?
    primitive 'push graphic-context'
  else
    primitive 'push ' + what.map { |x| to_string(x) }.join(' ')
  end
end

#rectangle(upper_left_x, upper_left_y, lower_right_x, lower_right_y) ⇒ Object

Draw a rectangle



533
534
535
536
537
538
# File 'lib/rmagick_internal.rb', line 533

def rectangle(upper_left_x, upper_left_y, lower_right_x, lower_right_y)
  primitive 'rectangle ' + sprintf(
    '%g,%g %g,%g',
    upper_left_x, upper_left_y, lower_right_x, lower_right_y
  )
end

#rotate(angle) ⇒ Object

Specify coordinate space rotation. "angle" is measured in degrees



541
542
543
# File 'lib/rmagick_internal.rb', line 541

def rotate(angle)
  primitive 'rotate ' + sprintf('%g', angle)
end

#roundrectangle(center_x, center_y, width, height, corner_width, corner_height) ⇒ Object

Draw a rectangle with rounded corners



546
547
548
549
550
551
# File 'lib/rmagick_internal.rb', line 546

def roundrectangle(center_x, center_y, width, height, corner_width, corner_height)
  primitive 'roundrectangle ' + sprintf(
    '%g,%g,%g,%g,%g,%g',
    center_x, center_y, width, height, corner_width, corner_height
  )
end

#scale(x, y) ⇒ Object

Specify scaling to be applied to coordinate space on subsequent drawing commands.



554
555
556
# File 'lib/rmagick_internal.rb', line 554

def scale(x, y)
  primitive 'scale ' + sprintf('%g,%g', x, y)
end

#skewx(angle) ⇒ Object



558
559
560
# File 'lib/rmagick_internal.rb', line 558

def skewx(angle)
  primitive 'skewX ' + sprintf('%g', angle)
end

#skewy(angle) ⇒ Object



562
563
564
# File 'lib/rmagick_internal.rb', line 562

def skewy(angle)
  primitive 'skewY ' + sprintf('%g', angle)
end

#stroke(colorspec) ⇒ Object Also known as: stroke_color, stroke_pattern

Specify the object stroke, a color name or pattern name.



567
568
569
# File 'lib/rmagick_internal.rb', line 567

def stroke(colorspec)
  primitive "stroke #{enquote(colorspec)}"
end

#stroke_antialias(bool) ⇒ Object

Specify if stroke should be antialiased or not



574
575
576
577
# File 'lib/rmagick_internal.rb', line 574

def stroke_antialias(bool)
  bool = bool ? '1' : '0'
  primitive "stroke-antialias #{bool}"
end

#stroke_dasharray(*list) ⇒ Object

Specify a stroke dash pattern



580
581
582
583
584
585
586
587
588
589
# File 'lib/rmagick_internal.rb', line 580

def stroke_dasharray(*list)
  if list.empty?
    primitive 'stroke-dasharray none'
  else
    list.map! { |x| Float(x) }.each do |x|
      Kernel.raise ArgumentError, "dash array elements must be > 0 (#{x} given)" if x <= 0
    end
    primitive "stroke-dasharray #{list.join(',')}"
  end
end

#stroke_dashoffset(value = 0) ⇒ Object

Specify the initial offset in the dash pattern



592
593
594
# File 'lib/rmagick_internal.rb', line 592

def stroke_dashoffset(value = 0)
  primitive 'stroke-dashoffset ' + sprintf('%g', value)
end

#stroke_linecap(value) ⇒ Object



596
597
598
599
600
# File 'lib/rmagick_internal.rb', line 596

def stroke_linecap(value)
  value = to_string(value)
  Kernel.raise ArgumentError, "Unknown linecap type: #{value}" unless %w[butt round square].include?(value.downcase)
  primitive "stroke-linecap #{value}"
end

#stroke_linejoin(value) ⇒ Object



602
603
604
605
606
# File 'lib/rmagick_internal.rb', line 602

def stroke_linejoin(value)
  value = to_string(value)
  Kernel.raise ArgumentError, "Unknown linejoin type: #{value}" unless %w[round miter bevel].include?(value.downcase)
  primitive "stroke-linejoin #{value}"
end

#stroke_miterlimit(value) ⇒ Object



608
609
610
611
612
# File 'lib/rmagick_internal.rb', line 608

def stroke_miterlimit(value)
  value = Float(value)
  Kernel.raise ArgumentError, 'miterlimit must be >= 1' if value < 1
  primitive "stroke-miterlimit #{value}"
end

#stroke_opacity(opacity) ⇒ Object

Specify opacity of stroke drawing color (use "xx%" to indicate percentage)



616
617
618
619
# File 'lib/rmagick_internal.rb', line 616

def stroke_opacity(opacity)
  opacity = to_opacity(opacity)
  primitive "stroke-opacity #{opacity}"
end

#stroke_width(pixels) ⇒ Object

Specify stroke (outline) width in pixels.



622
623
624
# File 'lib/rmagick_internal.rb', line 622

def stroke_width(pixels)
  primitive 'stroke-width ' + sprintf('%g', pixels)
end

#text(x, y, text) ⇒ Object

Draw text at position x,y. Add quotes to text that is not already quoted.



627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/rmagick_internal.rb', line 627

def text(x, y, text)
  text = to_string(text)
  Kernel.raise ArgumentError, 'missing text argument' if text.empty?
  # escape existing backslashes, so that they cannot escape the delimiter
  # added below and let the rest of the string be parsed as MVG
  text = text.gsub('\\') { |b| '\\' + b }
  if text.length > 2 && /\A(?:"[^"\\]+"|'[^'\\]+'|\{[^}\\]+\})\z/.match(text)
  # text already quoted
  elsif !text['\'']
    text = '\'' + text + '\''
  elsif !text['"']
    text = '"' + text + '"'
  elsif !(text['{'] || text['}'])
    text = '{' + text + '}'
  else
    # escape existing braces, surround with braces
    text = '{' + text.gsub(/[}]/) { |b| '\\' + b } + '}'
  end
  primitive 'text ' + sprintf('%g,%g %s', x, y, text)
end

#text_align(alignment) ⇒ Object

Specify text alignment relative to a given point



649
650
651
652
# File 'lib/rmagick_internal.rb', line 649

def text_align(alignment)
  Kernel.raise ArgumentError, "Unknown alignment constant: #{alignment}" unless ALIGN_TYPE_NAMES.key?(alignment.to_i)
  primitive "text-align #{ALIGN_TYPE_NAMES[alignment.to_i]}"
end

#text_anchor(anchor) ⇒ Object

SVG-compatible version of text_align



655
656
657
658
# File 'lib/rmagick_internal.rb', line 655

def text_anchor(anchor)
  Kernel.raise ArgumentError, "Unknown anchor constant: #{anchor}" unless ANCHOR_TYPE_NAMES.key?(anchor.to_i)
  primitive "text-anchor #{ANCHOR_TYPE_NAMES[anchor.to_i]}"
end

#text_antialias(boolean) ⇒ Object

Specify if rendered text is to be antialiased.



661
662
663
664
# File 'lib/rmagick_internal.rb', line 661

def text_antialias(boolean)
  boolean = boolean ? '1' : '0'
  primitive "text-antialias #{boolean}"
end

#text_undercolor(color) ⇒ Object

Specify color underneath text



667
668
669
# File 'lib/rmagick_internal.rb', line 667

def text_undercolor(color)
  primitive "text-undercolor #{enquote(color)}"
end

#translate(x, y) ⇒ Object

Specify center of coordinate space to use for subsequent drawing commands.



673
674
675
# File 'lib/rmagick_internal.rb', line 673

def translate(x, y)
  primitive 'translate ' + sprintf('%g,%g', x, y)
end