diff --git a/dlib/image_transforms/draw.h b/dlib/image_transforms/draw.h index 53b28f9ee..c38db500e 100644 --- a/dlib/image_transforms/draw.h +++ b/dlib/image_transforms/draw.h @@ -68,6 +68,13 @@ namespace dlib } else { + // This part is a little more complicated because we are going to perform alpha + // blending so the diagonal lines look nice. + const rectangle valid_area = get_rect(c); + rgb_alpha_pixel alpha_pixel; + assign_pixel(alpha_pixel, val); + const unsigned char max_alpha = alpha_pixel.alpha; + const long rise = (((long)y2) - ((long)y1)); const long run = (((long)x2) - ((long)x1)); if (std::abs(rise) < std::abs(run)) @@ -80,13 +87,13 @@ namespace dlib if (x1 > x2) { - first = x2; - last = x1; + first = std::max(x2,valid_area.left()); + last = std::min(x1,valid_area.right()); } else { - first = x1; - last = x2; + first = std::max(x1,valid_area.left()); + last = std::min(x2,valid_area.right()); } long y; @@ -95,18 +102,23 @@ namespace dlib const double y1f = y1; for (double i = first; i <= last; ++i) { - y = static_cast(slope*(i-x1f) + y1f); - x = static_cast(i); + const double dy = slope*(i-x1f) + y1f; + const double dx = i; + + y = static_cast(dy); + x = static_cast(dx); - if (y < 0 || y >= c.nr()) - continue; - - if (x < 0 || x >= c.nc()) - continue; - - - assign_pixel(c[y][x] , val); + if (y >= valid_area.top() && y <= valid_area.bottom()) + { + alpha_pixel.alpha = static_cast((1.0-(dy-y))*max_alpha); + assign_pixel(c[y][x], alpha_pixel); + } + if (y+1 >= valid_area.top() && y+1 <= valid_area.bottom()) + { + alpha_pixel.alpha = static_cast((dy-y)*max_alpha); + assign_pixel(c[y+1][x], alpha_pixel); + } } } else @@ -119,33 +131,37 @@ namespace dlib if (y1 > y2) { - first = y2; - last = y1; + first = std::max(y2,valid_area.top()); + last = std::min(y1,valid_area.bottom()); } else { - first = y1; - last = y2; + first = std::max(y1,valid_area.top()); + last = std::min(y2,valid_area.bottom()); } - long x; long y; const double x1f = x1; const double y1f = y1; for (double i = first; i <= last; ++i) { - x = static_cast(slope*(i-y1f) + x1f); - y = static_cast(i); + const double dx = slope*(i-y1f) + x1f; + const double dy = i; + y = static_cast(dy); + x = static_cast(dx); - if (x < 0 || x >= c.nc()) - continue; - - if (y < 0 || y >= c.nr()) - continue; - - assign_pixel(c[y][x] , val); + if (x >= valid_area.left() && x <= valid_area.right()) + { + alpha_pixel.alpha = static_cast((1.0-(dx-x))*max_alpha); + assign_pixel(c[y][x], alpha_pixel); + } + if (x+1 >= valid_area.left() && x+1 <= valid_area.right()) + { + alpha_pixel.alpha = static_cast((dx-x)*max_alpha); + assign_pixel(c[y][x+1], alpha_pixel); + } } } }