Draw on BufferedImage with transparent background Java
If your Buffered Image has transparent background & you want to use transparent color to draw to solve erase purpose then follow the code given below.
void eraseCanvase(int x1, int y1, int x2, int y2) {
int eraserWidth=10;
Graphics g = OSC.getGraphics();
int dist = Math.max(Math.abs(x2-x1),Math.abs(y2-y1));
double dx = (double)(x2-x1)/dist;
double dy = (double)(y2-y1)/dist;
for (int d = 1; d <= dist; d++) {
int x = (int)Math.round(x1 + dx*d);
int y = (int)Math.round(y1 + dy*d);
// Erase a 10-by-10 block by default of pixels around (x,y) Customizable.
if( g instanceof Graphics2D ){
Graphics2D g2d = (Graphics2D) g;
// make sure the background is filled with transparent pixels when cleared !
g2d.setBackground(new Color(0,0,0,0));
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_IN, 0.0f));
g.clearRect(x-3, y-3, eraserWidth, eraserWidth);
}
repaint(x-3,y-3,eraserWidth,eraserWidth);
}
In code you can change the eraserWidth value as per desired ie. to make size of eraser.You should use it in case of mouse dragged event .
But if u want to use Eraser on white color BufferedImage the just follow the code
void eraseCanvase(int x1, int y1, int x2, int y2) {
int eraserWidth=10;
Graphics g = OSC.getGraphics();
g.setColor(Color.WHITE);
int dist = Math.max(Math.abs(x2-x1),Math.abs(y2-y1));
double dx = (double)(x2-x1)/dist;
double dy = (double)(y2-y1)/dist;
for (int d = 1; d <= dist; d++) {
int x = (int)Math.round(x1 + dx*d);
int y = (int)Math.round(y1 + dy*d);
// Erase a 10-by-10 block by default of pixels around (x,y) Customizable.
// Erase a 10-by-10 block of pixels around (x,y)
g.fillRect(x-eraserWidth/2,y-eraserWidth/2,eraserWidth,eraserWidth);
repaint(x-eraserWidth/2,y-eraserWidth/2,eraserWidth,eraserWidth);
}
No comments:
Post a Comment